有没有办法对行的值求和?

时间:2015-10-15 15:56:15

标签: mysql sql

我有一个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

结果是:

enter image description here

但我想要SUM这些列。预期结果 17 (3 + 4 + 3 + 3 + 4)。

有没有解决方案?

2 个答案:

答案 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