繁体   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