Mysql - 显示基于月份和年份的所有计数行

时间:2017-03-06 08:25:42

标签: php mysql

如何根据特定年份和月份计算记录?例如,我想做的如下,

|  Category | Total  |
|-----------|--------|
|  Cat 1    |  15    |
|  Cat 2    |  0     |
|  Cat 3    |  20    |
|  Cat 4    |  18    |

这是我做的查询,

SELECT kc.jenis_katCuti, count(pc.id) AS jum_cuti
FROM permohonan_cuti pc
RIGHT JOIN kat_cuti kc on kc.katCuti_id=pc.katCuti_id
WHERE YEAR(pc.tarikh_mula)=2017 AND MONTH(pc.tarikh_mula)=1
GROUP BY kc.jenis_katCuti

从查询中,它仅会显示用户选择的YearMonth。如果没有特定月份和年份的记录,我希望它显示所有记录并返回0

我也在下面试过,但仍然没有成功

SELECT kc.jenis_katCuti, count(YEAR(pc.tarikh_mula)=2017 
AND MONTH(pc.tarikh_mula)=1) AS jum_cuti
FROM permohonan_cuti pc
RIGHT JOIN kat_cuti kc on kc.katCuti_id=pc.katCuti_id
GROUP BY kc.jenis_katCuti

1 个答案:

答案 0 :(得分:1)

case when中使用count,如下所示:

SELECT 
    kc.jenis_katCuti,
    count(CASE WHEN YEAR(pc.tarikh_mula) = 2017 AND MONTH(pc.tarikh_mula) = 1 THEN 1 ELSE NULL END) AS jum_cuti
FROM permohonan_cuti pc
RIGHT JOIN kat_cuti kc on kc.katCuti_id = pc.katCuti_id
GROUP BY kc.jenis_katCuti

原因count仅排除null,表达式YEAR(pc.tarikh_mula) = 2017 AND MONTH(pc.tarikh_mula) = 1将返回1或0,count将包含这两者。

如果您只使用YEAR(pc.tarikh_mula) = 2017 AND MONTH(pc.tarikh_mula) = 1,请尝试sum

SELECT 
    kc.jenis_katCuti,
    sum(YEAR(pc.tarikh_mula) = 2017 AND MONTH(pc.tarikh_mula) = 1) AS jum_cuti
FROM permohonan_cuti pc
RIGHT JOIN kat_cuti kc on kc.katCuti_id = pc.katCuti_id
GROUP BY kc.jenis_katCuti