MySql - 如何找出哪个月添加了最多的囚犯

时间:2014-05-14 15:49:38

标签: mysql sql date group-by

我有两张桌子,囚犯和人。

Prisoner:
prisoner_id
person_ssn
sentence_start 
sentence_end

Person
first_name
last_name
person_ssn

如果sentence_start字段属于DATE类型,我是否可以计算哪个月添加了最多的囚犯,然后显示该月份以及有多少个?

1 个答案:

答案 0 :(得分:2)

您只需按月和可能年份运行COUNT查询和GROUP结果:

SELECT   YEAR(sentence_start) AS Y, MONTH(sentence_start) AS M, COUNT(*) AS C
FROM prisoner
GROUP BY YEAR(sentence_start), MONTH(sentence_start)

也可以使用MySQL EXTRACT函数更快地获得相同的结果:

SELECT   EXTRACT(YEAR_MONTH FROM sentence_start) AS YM, COUNT(*) AS C
FROM prisoner
GROUP BY EXTRACT(YEAR_MONTH FROM sentence_start)