用AND时的情况?

时间:2012-06-15 12:40:52

标签: mysql sql database

我想将Case WhenAND条件一起使用,而不是正确计算总和。

例如:

SELECT DATE(`SubmitDate`), 
     SUM(CASE status WHEN 'New' AND `Type` = 'consumer' THEN 1 ELSE 0 END) as new_consumer,
     SUM(CASE status WHEN 'New' AND `Type` = 'business' THEN 1 ELSE 0 END) as new_business
FROM report
WHERE `source` = 'net'
group by DATE(`SubmitDate`) Order by `SubmitDate` DESC

2 个答案:

答案 0 :(得分:6)

您需要使用CASE WHEN [Condition] THEN...而不是简单的案例表达式:

SELECT DATE(`SubmitDate`), 
     SUM(CASE WHEN status = 'New' AND `Type` = 'consumer' THEN 1 ELSE 0 END) as new_consumer,
     SUM(CASE WHEN status = 'New' AND `Type` = 'business' THEN 1 ELSE 0 END) as new_business
FROM report
WHERE `source` = 'net'
group by DATE(`SubmitDate`) Order by `SubmitDate` DESC

答案 1 :(得分:3)

你应该写

CASE  WHEN status='New' AND `Type` = 'consumer' THEN 1 ELSE 0 END

检查CASE WHEN

的语法