我正在使用此查询:

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完成此操作,但是我对此的了解太少了...

最佳答案

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

07-27 21:10