簡體   English   中英

兩個sql查詢合而為一

[英]Two sql query as one

有兩個sql查詢,我想寫為一個查詢。 第二個查詢顯示不同記錄的計數,其中action_text如'%STAFF%'。 我嘗試使用UNION,但是沒有用。

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

據我所知,第二個查詢中唯一的新列是COUNT(DISTINCT order_number) ... WHERE action_text LIKE '%STAFF%'

然后,您可以將COUNT(DISTINCT IF(action-text LIKE '%STAFF%',order_number,NULL)) as unique_orderstouched為原始查詢的COUNT(DISTINCT IF(action-text LIKE '%STAFF%',order_number,NULL)) as unique_orderstouched

(我也假設表stats.sales_actions在第一個查詢相同的表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

如果進行並集,則兩個查詢之間選擇的列必須相同。 您需要具有相同數量的列,相同的數據類型,並且它們必須具有相同的順序。 在第一個查詢中,您選擇四個列,第二個查詢中僅選擇兩個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM