MySQL计数与案例返回错误计数

时间:2015-01-08 23:03:44

标签: mysql case

我有以下问题:

我有mysql表:

continent,  
country,  
city,  
zip,  
street,  
status (int),  
reason (varchar, can be empty or some text),  
... (some other columns, not required for query)  

我希望通过 country,city,zip,street 计算每个状态的出现次数,但是将状态int映射到文本:

SELECT country,city,zip,street, 
   CASE WHEN (status = '2' AND reason <> '') THEN "BLOCKED" 
        WHEN (status = '2' AND reason='') THEN "DISPUTED"  
        WHEN status = '3' THEN 'EXPIRED' 
        WHEN status = '1' THEN 'ACTIVE' ELSE 'UNKNOWN' 
        END as status, 
    count(*) AS count
FROM people
where continent='Europe'
GROUP BY country,city,zip,street,status

我认为问题出现在GROUP BY中但不确定 - 它不会返回正确的数据。

SQLFiddle (检查Paris / Street2 - 它显示3 DISPUTED,应该显示1 BLOCKED和2 DISPUTED)

感谢您的意见。

1 个答案:

答案 0 :(得分:2)

我认为EngineerCoder 打算写

select country,city,zip,street, status, count(*) 
from
(
SELECT country,city,zip,street, 
   CASE WHEN (status = '2' AND reason <> '') THEN "BLOCKED" 
        WHEN (status = '2' AND reason='') THEN "DISPUTED"  
        WHEN status = '3' THEN 'EXPIRED' 
        WHEN status = '1' THEN 'ACTIVE' ELSE 'UNKNOWN' 
   END as status, 
FROM people
where continent='Europe'
) AS ilv
GROUP BY country,city,zip,street,status
相关问题