2012-02-07 3 views
0

두 개의 SQL 쿼리가 하나의 쿼리로 작성하고 싶습니다. 두 번째 쿼리는 '% STAFF %'와 (와) 같이 action_text가 다른 레코드의 수를 표시합니다. UNION을 사용해 보았지만 작동하지 않았습니다.하나의 SQL 쿼리 두 개로

select date(dated) date_ord, 
count(DISTINCT order_number) as orders_placed, 
sum(case when action_text like '%STAFF%' then 1 else 0 end) AS orders_staff, 
sum(case when action_text in (
       'CBA Capture attempt', 
       'GCO Capture attempt', 
       'PPP Capture', 
       'PPE Capture', 
       'Staff CC capture', 
       'Web CC capture', 
       'Staff Finance WIRE authorized', 
       'Staff Finance PO authorized', 
       'Staff Finance COD authorized', 
       'Authorized The CPIC') then 1 else 0 end)  AS  orders_manuallycaptured 
from stats.sales_actions 
group by date_ord 
order by dated desc 


SELECT COUNT(DISTINCT order_number) as unique_orderstouched, 
date(dated) date_ords 
FROM sales_actions 
WHERE action_text like '%STAFF%' 
group by date_ords 
order by dated desc 

답변

1

내가 알 수있는 한 두 번째 쿼리의 유일한 새로운 열은 COUNT(DISTINCT order_number) ... WHERE action_text LIKE '%STAFF%'입니다.

그러면 원래 검색어에 COUNT(DISTINCT IF(action-text LIKE '%STAFF%',order_number,NULL)) as unique_orderstouched을 추가 할 수 있습니다.

(첫 번째 쿼리의 테이블 stats.sales_actions은 두 번째 쿼리의 테이블 sales_actions과 동일하다고 가정합니다.). 당신은 또한 당신의 SUM(CASE WHEN condition THEN 1 ELSE 0) 같은 것으로 생각할 수 있지만,에 DISTINCT와 -

select date(dated) date_ord, 
count(DISTINCT order_number) as orders_placed, 
sum(case when action_text like '%STAFF%' then 1 else 0 end) AS orders_staff, 
sum(case when action_text in (
       'CBA Capture attempt', 
       'GCO Capture attempt', 
       'PPP Capture', 
       'PPE Capture', 
       'Staff CC capture', 
       'Web CC capture', 
       'Staff Finance WIRE authorized', 
       'Staff Finance PO authorized', 
       'Staff Finance COD authorized', 
       'Authorized The CPIC') then 1 else 0 end) AS orders_manuallycaptured, 
-- new line follows 
COUNT(DISTINCT IF(action-text LIKE '%STAFF%',order_number,NULL)) 
    AS unique_orderstouched 
from stats.sales_actions 
group by date_ord 
order by dated desc 

COUNT(DISTINCT IF(condition, order_number, NULL))COUNT(DISTINCT order_number) ... WHERE <condition> 말과 같다 :

당신은 끝낼 것입니다.

+1

날짜 주문 주문 완료 주문 수동 캡처 독특한 주문 는 2012-02-01 122 340 169 102 156 271 143 2012-01-31 78 126 2012-02-03 2,012 329 162 77 135 299 148 2012-02-02 터치 -01-30 436 211 129 187 2012-01-27 275 138 66 112 2012-01-26 318 150 87 128 2012-01-25 297 145 91 152 2012-01-24 163 77 60 87 – rachel

+0

감사합니다. :) 그것은 일했다. 좋은 하루 보내라. – rachel

0

공용어를 사용하는 경우 선택한 열은 두 쿼리간에 동일해야합니다. 동일한 수의 열, 동일한 데이터 유형이 있어야하며 같은 순서로 있어야합니다. 첫 번째 쿼리에서는 네 개의 열을 선택하고 두 번째 쿼리는 두 개만 선택합니다.

+1

그런 다음 영혼이 될 수있는 것은 무엇입니까? – rachel

+0

해결책의 첫 번째 단계는 당신이 얻고 자하는 결과의 예제를 추가하여 답을 편집하는 것입니다. –

+0

정확히 당신이 당신의 질문으로 무엇을하려고하는지 조금 더 자세히 설명해 주시겠습니까? – nolt2232

관련 문제