mysql - 如何执行此查询 : multiple distinct counts

标签 mysql

我有一个包含以下行的 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/

相关文章:

mysql - 查询以匹配一列中的不同值,而该列中的不同值在单独的列中具有相同的值

php - 从数据库中读取,单行(Joomla 框架)

php - 动态 <div> 内容变化 <select>

java - 测试对唯一标识符的查询是否最多返回一个结果

mysql - 我需要从其他数据库加入表,有时还需要从其他服务器加入表

mysql - 如何从表 MYSQL 中获取最后输入的 id 条目

php - MYSQL 搜索脚本 php 的错误结果

mysql - 将最新的 InnoDB_Rows_Inserted 变量值与旧值进行比较

mysql - mysql如何引用列中的数据

c# - 执行Mysql查询时命令执行过程中遇到 fatal error