使用“选择”子查询进行分组

时间:2018-03-03 22:03:27

标签: sql

我正在尝试按工作日对表格进行分组,因此我可以看到每种付款类型的计数以及按工作日分割的其他销售信息。但是,因为我正在使用子查询,所以我只得到一个重复值列表,因为子查询只能返回一个值。有没有一种简单的方法可以按工作日分组?我想我在别处读过我可能要为每个子查询做一系列连接,但是因为有8个子查询,我宁愿不这样做。我目前的代码如下:

select datename(weekday, transaction_date) as [Day],
(select count(tender_type) from store_visits where tender_type = '0') as [Cash],
(select count(tender_type) from store_visits where tender_type = '1') as [Check],
(select count(tender_type) from store_visits where tender_type = '2') as [Gift Card],
(select count(tender_type) from store_visits where tender_type = '3') as [Discover],
(select count(tender_type) from store_visits where tender_type = '4') as [Direct Credit],
(select count(tender_type) from store_visits where tender_type = '5') as [Business Credit],
(select count(tender_type) from store_visits where tender_type = '6') as [Personal Credit],
(select count(tender_type) from store_visits where tender_type = '7' or tender_type = '8' or tender_type = '9') as [Other] 
from store_visits group by datename(weekday, transaction_date)

1 个答案:

答案 0 :(得分:1)

这称为条件聚合。在case中使用count表达式。

select datename(weekday, transaction_date) as [Day],
count(case when tender_type = '0' then 1 end) as [Cash],
count(case when tender_type = '1' then 1 end) as [Check],
count(case when tender_type = '2' then 1 end) as [Gift Card],
count(case when tender_type = '3' then 1 end) as [Discover],
count(case when tender_type = '4' then 1 end) as [Direct Credit],
count(case when tender_type = '5' then 1 end) as [Business Credit],
count(case when tender_type = '6' then 1 end) as [Personal Credit],
count(case when tender_type in ('7','8','9') then 1 end) as [Other] 
from store_visits
group by datename(weekday, transaction_date)