一尘不染

MySql:是否可以'SUM IF'或'COUNT IF'?

mysql

我有一个“小时”列,我有一个“种类”列(可以是1,2或3)

我想做类似的事情:

SELECT count(id), SUM(hour) as totHour, SUM( IF ( kind = 1, 1, 0 ) ) as countKindOne

要么

SELECT count(id), SUM(hour) as totHour, COUNT( IF ( kind = 1 ) ) as countKindOne

但是mysql告诉我我有一个错误…什么是错误!

请参见以下stackoverflow主题:MySQL SUM IF字段b
=字段a

..我无法回复此邮件…


阅读 364

收藏
2020-05-17

共1个答案

一尘不染

您可以使用以下CASE语句:

SELECT count(id), 
    SUM(hour) as totHour, 
    SUM(case when kind = 1 then 1 else 0 end) as countKindOne
2020-05-17