Mysql多次计数和选择

时间:2013-02-07 06:01:52

标签: mysql sql

大家好,我正在尝试计算特定ID的具体项目

db result

name                      remarks
joseph greggory           On time
joseph greggory           On time
lara joy                  On time
lara joy                  Absent
Mark Joben                On time
Mark Joben                Absent
Isnaira Lyn               Absent
Isnaira Lyn               Absent

结果应该是

name                  On time         Late       Absent
joseph Greggory         2              0            0
Lara Joy                1              0            1
Mark Joben              1              0            1
Isnaira Lyn             0              0            2

提前谢谢你们

3 个答案:

答案 0 :(得分:4)

SELECT  name,
        SUM(CASE WHEN remarks = 'On time' THEN 1 ELSE 0 END) `On time`,
        SUM(CASE WHEN remarks = 'Late' THEN 1 ELSE 0 END) `Late`,
        SUM(CASE WHEN remarks = 'Absent' THEN 1 ELSE 0 END) `Absent`  
FROM    TableName
GROUP   BY name

答案 1 :(得分:0)

你可以试试这个,

select name,
       count(case when remarks = 'On time' then 1 end) "On time",
       count(case when remarks = 'Late' then 1 end) "Remarks",
       count(case when remarks = 'Absent' then 1 end) "Absent"
from table1
group by name;

<强> SQL FIDDLE OUTPUT

答案 2 :(得分:0)

你可以试试这个:

SELECT  name,
        COUNT(IF(remarks = 'On time', 1, NULL)) `On time`,
        COUNT(IF(remarks = 'Late', 1, NULL)) `Late`,
        COUNT(IF(remarks = 'Absent', 1, NULL)) `Absent`  
FROM    tbl
GROUP   BY name