2012-02-07 56 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