用于检索多个Counts的SQL语句

时间:2013-02-18 23:49:18

标签: mysql sql count

table account:
    acID (pri, uni, a-i)
    ...

table patient:
    paID (pri, uni, a-i)
    paAccountID (int, foreign key)
    ...

table test:
    tsID (pri, uni, a-i)
    tsAccountID (int, foreign key)
    tsPatientID (int, foreign key)
    tsStatus (int, ranges 0 to 3)
    tsFlag (int, ranges 0 to 1)

为每位患者检索patient的数据和tsID的数量:

SELECT patient.*, Count(tsID) as tsCount   
FROM account 
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID

现在,我想检索tsFlag=1的数量,tsStatus=0的数量,'tsStatus = 1'的数量...... tsStatus=3的数量。

感谢Explosion Pill的回答:

SELECT patient.*, Count(tsID), SUM(tsStatus=0), 
SUM(tsStatus=1), SUM(tsStatus=2), SUM(tsStatus=3), SUM(tsFlag=1)
FROM account 
LEFT JOIN patient ON acID = paAccountID
LEFT JOIN test ON paID = tsPatientID
WHERE paAccountID=1
GROUP BY paID

像魅力一样工作,但如果NULLSUM提供Count=0 - 我怎样才能获得0

1 个答案:

答案 0 :(得分:3)

您可以使用SUM

获取X = Y的计数
SELECT patient.*, SUM(tsStatus = 1) AS tsStatus1
FROM ...

您也可以为其他列执行此操作。

您可以使用IFNULLCOALESCE指定默认的非空值:

IFNULL(SUM(tsStatus = 3), 0);