我有一个SQL QUERY,即我使用SUM
:
SELECT
SUM(CASE WHEN `ID_Event1` != 0 THEN 1 ELSE 0 END) AS count1,
SUM(CASE WHEN `ID_Event2` != 0 THEN 1 ELSE 0 END) AS count2,
SUM(CASE WHEN `ID_Event3` != 0 THEN 1 ELSE 0 END) AS count3,
SUM(CASE WHEN `ID_Event4` != 0 THEN 1 ELSE 0 END) AS count4,
SUM(CASE WHEN `ID_Event5` != 0 THEN 1 ELSE 0 END) AS count5
FROM `ec_calendar` WHERE Year(`Day`)=2015 AND Month(`Day`)=6
结果是:
但我想要SUM
这些列。预期结果 17 (3 + 4 + 3 + 3 + 4)。
有没有解决方案?
答案 0 :(得分:3)
然后使用+
:
SELECT (SUM(CASE WHEN `ID_Event1` != 0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN `ID_Event2` != 0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN `ID_Event3` != 0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN `ID_Event4` != 0 THEN 1 ELSE 0 END) +
SUM(CASE WHEN `ID_Event5` != 0 THEN 1 ELSE 0 END)
) as cnt
FROM `ec_calendar`
WHERE day >= '2015-06-01' and day < '2015-07-01'
请注意,我更改了WHERE
子句。如果您在day
上有索引,则此方法效率更高。
MySQL将布尔值视为整数,因此您可以将其写为:
SELECT (SUM(ID_Event1 <> 0) + SUM(ID_Event2 <> 0) +
SUM(ID_Event3 <> 0) + SUM(ID_Event4 <> 0) +
SUM(ID_Event5 <> 0)
) as cnt
FROM `ec_calendar`
WHERE day >= '2015-06-01' and day < '2015-07-01'
答案 1 :(得分:2)
您只需添加计算列即可。
SELECT
SUM(CASE WHEN `ID_Event1` != 0 THEN 1 ELSE 0 END) AS count1,
SUM(CASE WHEN `ID_Event2` != 0 THEN 1 ELSE 0 END) AS count2,
SUM(CASE WHEN `ID_Event3` != 0 THEN 1 ELSE 0 END) AS count3,
SUM(CASE WHEN `ID_Event4` != 0 THEN 1 ELSE 0 END) AS count4,
SUM(CASE WHEN `ID_Event5` != 0 THEN 1 ELSE 0 END) AS count5,
SUM(CASE WHEN `ID_Event1` != 0 THEN 1 ELSE 0 END)+
SUM(CASE WHEN `ID_Event2` != 0 THEN 1 ELSE 0 END)+
SUM(CASE WHEN `ID_Event3` != 0 THEN 1 ELSE 0 END)+
SUM(CASE WHEN `ID_Event4` != 0 THEN 1 ELSE 0 END)+
SUM(CASE WHEN `ID_Event5` != 0 THEN 1 ELSE 0 END) as total
FROM `ec_calendar` WHERE Year(`Day`)=2015 AND Month(`Day`)=6