对具有多个ID的行求和

时间:2012-01-15 13:31:12

标签: mysql select sum

我正在使用此查询:

SELECT SUM(voc=1) AS s, SUM(voc=2) AS d, SUM(voc=3) AS p FROM `pl`;

但是现在我需要修改此查询,因此当SUM等于多个数字时它会voc

SELECT SUM ( voc = 1 OR voc = 7 OR voc = 3 ) as `s` FROM `pl`;

不幸的是,以上操作不正常,我已经读过这可以使用CASE完成,但我对此的了解太少了......

1 个答案:

答案 0 :(得分:3)

SELECT SUM ( CASE WHEN voc = 1 OR voc = 7 OR voc = 3 THEN 1 ELSE 0 END) as `s` FROM `pl`;

UPD 正如@Raul在评论中指出的那样 - WHERE应该更加有效,如下所示:

SELECT COUNT(*) AS `s` FROM `p1` WHERE voc IN (1,3,7);

UPD2 将总和更改为计数 - 感谢@newtower