DATE数据每年的MYSQL COUNT

时间:2017-05-17 08:26:22

标签: mysql sql database

我需要问一些关于mysql中多个计数的问题,所以我有这样的数据:

|  name  |  date                        | act  |
------------------------------------------------
| abc    |  2014-02-03 07:05:18         |  1   |
| abc    |  2014-02-03 08:05:18         |  1   |
| abc    |  2015-02-03 07:05:18         |  1   |
| ghi    |  2014-02-03 07:05:18         |  1   |
| ghi    |  2015-02-03 07:05:18         |  1   |
| klm    |  2014-02-03 07:05:18         |  1   |
| klm    |  2014-04-01 07:05:18         |  1   |

然后我想做一个这样的报告:

|  name  |  count(2014)  |  count(2015)  |
------------------------------------------------
| abc    |       2       |      1        |
| ghi    |       1       |      1        |
| klm    |       2       |      0        |

如何进行计数查询?

1 个答案:

答案 0 :(得分:5)

如果年份是那两年,或者是有限的集合,您可以使用条件计数

select  name,
        sum(case when year(date) = 2014 then 1 else 0 end) as count_14,
        sum(case when year(date) = 2015 then 1 else 0 end) as count_15
from    yourTable
group by name

否则我会建议将年份移到行中,然后将其更改为表示层(或使用数据透视图)的列

select  name, year(date), count(*)
from    yourTable
group by name, year(date)