对SQL表达式执行计数

时间:2012-10-15 07:31:43

标签: mysql sql

我目前有查询:

SELECT count(*) as number_of_items,
    if(first_name <> "", 1, 0)
    + if(last_name <> "", 1, 0)
    + if(current_avatar is not null, 1, 0)
    + if(username <> "" 
        AND email <> "" 
        AND gender <> "" 
        AND date_of_birth <> "" ,1,0) AS completeness 
FROM `user` HAVING (completeness = '4')

但这不符合预期。它似乎计算它们都具有2的完整性。如果我删除计数并具有子句,它确实看到所有不同的完整性计数(从1到4)。有没有办法统计个人的完整性计数?

1 个答案:

答案 0 :(得分:2)

您需要group by completeness才能实现此目的:

SELECT count(*) as number_of_items,
    if(first_name <> "", 1, 0)
    + if(last_name <> "", 1, 0)
    + if(current_avatar is not null, 1, 0)
    + if(username <> "" 
        AND email <> "" 
        AND gender <> "" 
        AND date_of_birth <> "" ,1,0) AS completeness 
FROM `user`
GROUP BY completeness
HAVING (completeness = '4')