我有一个包含以下行的 mysql 表(我使用的是关系数据库,所以这只是一个示例):
id, start_date, person, how_heard, status
示例数据如下:
1, 2017-01-01, bob, newspaper, attended
2, 2017-02-03, steve, mail, no show
3, 2016-04-12, mary, newspaper, no show
4, 2015-12-12, rick, mail, cancel
...
...
我现在想要查询此表以查看按年份分组的每项营销工作的结果。
因此,对于 2017 年,我希望看到该报纸有 54 个独特的人员,并且有 2 人参加他们的约会,0 人未出现,1 人取消
因此报告的列将是:
year, how_heard, total_appointments, number_cancel, number_no_show, number_attended
我对如何执行此操作感到困惑。
这可以通过一个查询实现吗?
最佳答案
是的,这是可能的。 您需要按年份和 how_heard 进行分组,并使用 CASE 语句对其他列进行条件求和。我已经完成了第一个,除了更改等于条件和列名称之外,其余部分将相同
select year(start_date) year,
how_heard,
count(1) as total_appointments,
SUM(case when status = 'attended' then 1 else 0 end) as number_attended
from campaign
group by year(start_date), how_heard
查找 SQL Fiddle here
根据您的测试数据和上述查询,您将得到
year how_heard total_appointments number_attended
2015 mail 1 0
2016 newspaper 1 0
2017 mail 1 0
2017 newspaper 1 1
关于mysql - 如何执行此查询 : multiple distinct counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900133/