我可以使用Count Case来显示MySQL中的条件计数结果吗?

时间:2016-10-03 18:35:15

标签: mysql

我的数据库表结构中有一个名为 data 的数据库表,如下所示:

+----+------------+------+--------+---------+
| id |    date    | name | absent | late_in |
+----+------------+------+--------+---------+
|  1 | 2016-09-09 | John | Hadir  |      20 |
|  2 | 2016-09-09 | Sean | Hadir  |         |
|  3 | 2016-09-09 | Alea | Libur  |         |
|  4 | 2016-09-09 | Rina | Hadir  |         |
|  5 | 2016-09-08 | John | Hadir  |         |
|  6 | 2016-09-08 | Sean | Ijin   |         |
|  7 | 2016-09-08 | Alea | Hadir  |         |
|  8 | 2016-09-08 | Rina | Hadir  |      10 |
|  9 | 2016-09-07 | John | Sakit  |         |
| 10 | 2016-09-07 | Sean | Hadir  |         |
| 11 | 2016-09-07 | Alea | Hadir  |         |
| 12 | 2016-09-07 | Rina | Hadir  |         |
+----+------------+------+--------+---------+

我希望在Html中显示:

+------+-------+-------+------+------+-------+---------+
| Name | Hadir | Sakit | Ijin | Alpa | Libur | late_in |
+------+-------+-------+------+------+-------+---------+
| John |     2 |     1 |    - |    - |     - | 20 Min  |
| Sean |     2 |     - |    1 |    - |     - |      -  |
| Alea |     2 |     - |    - |    - |     1 |      -  |
| Rina |     3 |     - |    - |    - |     - | 10 Min  |
+------+-------+-------+------+------+-------+---------+

我尝试使用此查询

SELECT date, name, absent,
SUM(late_in) as late,
COUNT(CASE WHEN absent = 'Hadir' THEN absent ELSE 0 END) AS hadir, 
COUNT(CASE WHEN absent = 'Sakit' THEN absent ELSE 0 END) AS sakit, 
COUNT(CASE WHEN absent = 'Izin/Cuti' THEN absent ELSE 0 END) AS izin,
COUNT(CASE WHEN absent = 'Alpha' THEN absent ELSE 0 END) AS alpha,
FROM data GROUP BY name WHERE date between '$foo' and '$foo2' 

但我不知道为什么,没有数据要显示。

1 个答案:

答案 0 :(得分:1)

SELECT DISTINCT
    名称为'姓名',
    SUM(缺席的情况=' Hadir'那么1 ELSE null END)作为' Hadir',
    SUM(不存在的情况=' Sakit' THEN 1 ELSE null END)as' Sakit',
    SUM(当缺席的情况=' Ijin'那么1,结束时为空)作为' Ijin',
    SUM(缺席情况=' Alpa' THEN 1 ELSE null END)' Alpa',
    SUM(例如,当缺席=' Libur' THEN 1 ELSE null END)作为' Libur',
    SUM(late_in)as' late_in'
从      数据
GROUP BY名称
ORDER BY id ASC