2012-02-07 6 views
0

2つのsqlクエリがあり、1つのクエリとして書きたいと思います。 2番目のクエリは、 '%STAFF%'のようなaction_textの異なるレコードの数を表示します。 UNIONを使ってみましたが、動作しませんでした。2つのsqlクエリを1つとして

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

私が知る限り、2番目のクエリの唯一の新しい列は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テーブルは、2番目のクエリの​​テーブルと同じですか?)また、あなたの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-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

+0

ありがとう:)それは働いた..良い一日を – rachel

0

ユニオンを行う場合、選択する列は2つのクエリ間で同じである必要があります。同じ数の列、同じデータ型を持つ必要があり、同じ順序にする必要があります。最初のクエリでは4つの列を選択し、2つ目のクエリでは2つのみを選択します。

+1

[OK]を次に、何が魂ですか? – rachel

+0

解決策の第一歩は、回答を編集して、得ようとしている結果の例を追加することです。 –

+0

あなたはあなたの質問を正確に何をしようとしているのですか? – nolt2232