有两个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
答案 0 :(得分: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
相同?)。
你最终得到:
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 :(得分:0)
如果您进行联合,则您选择的列在两个查询之间必须相同。您需要具有相同数量的列,相同的数据类型,并且它们需要具有相同的顺序。在第一个查询中,您选择了四列,第二个查询只选择了两列。