我有两张桌子,囚犯和人。
Prisoner:
prisoner_id
person_ssn
sentence_start
sentence_end
Person
first_name
last_name
person_ssn
如果sentence_start字段属于DATE类型,我是否可以计算哪个月添加了最多的囚犯,然后显示该月份以及有多少个?
答案 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)