2012-02-07 61 views
0

有兩個sql查詢,我想寫爲一個查詢。 第二個查詢顯示action_text類似'%STAFF%'的不同記錄的計數。 我試過使用聯盟,但它沒有奏效。兩個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與第二個查詢中的表​​相同?)。

你會結束:

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> - 你也可以把它看成是像你SUM(CASE WHEN condition THEN 1 ELSE 0),但在它DISTINCT

+1

日期 訂單 的訂單 感動訂單手動 捕獲獨特訂單 觸摸 2012-02-03 329 162 77 135 2012-02-02 299 148 70 122 2012-02-01 340 169 102 156 2012-01-31 271 143 78 126 2012 -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 2012-02-07 06:29:06

+0

謝謝:)它的工作..有一個美好的一天 – rachel 2012-02-07 07:22:57

0

如果你做了一個聯合,你選擇的列需要在兩個查詢之間保持一致。您需要具有相同數量的列,相同的數據類型,並且它們需要具有相同的順序。在第一個查詢中,您選擇四列,第二個查詢只選擇兩列。

+1

好吧然後什麼可能是靈魂呢? – rachel 2012-02-07 05:36:11

+0

該解決方案的第一步是編輯您的答案,並添加您期望得到的結果的示例 – 2012-02-07 06:02:18

+0

您能詳細闡述一下您在嘗試處理查詢的方式嗎? – nolt2232 2012-02-07 06:06:01