我想按年计算两个字段
我试试
SELECT YEAR(admit_date),COUNT(sub_case),COUNT(SK)
FROM admit
WHERE sub_case = "scase001"
AND SK = "rsk002"
GROUP BY YEAR(admit_date),sub_case,SK
但事实并非如此
表
总计
真
2014 1 0
2015 1 1
答案 0 :(得分:1)
您需要从GROUP BY
SELECT YEAR(admit_date),COUNT(sub_case),SUM(CASE WHEN SK="rsk002" THEN 1 ELSE 0 END)
FROM admit
WHERE sub_case = "scase001"
GROUP BY YEAR(admit_date)
答案 1 :(得分:1)
您可以使用条件聚合,如下所示:
SELECT
YEAR(admit_date) AS "admit_year",
SUM(sub_case = 'scase001') AS "sub_case_count",
SUM(SK = 'rsk002') AS "sk_count"
FROM admit
GROUP BY YEAR(admit_date)
对于所有匹配的行,表达式sub_case = 'scase001'
将评估为1,并且总结匹配与计算它们相同。以这种方式使用(或滥用)布尔表达式可能在其他SQL数据库中不起作用,但它在MySQL中起作用(通常会使用case when ... then .. end
表达式。)