对具有相同属性的两个条件使用sum

siv3szwd  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(242)

当我创建一个表来计算18-40之间的用户时,我需要在表达式中有两个关于生日的条件,比如 sum((age>=18 and age<=40) and (Gender='M')) ,但是这个的返回值总是等于0,整个查询和输出如下,(mysql 5.30)

create table AgeUser
        select
                Id as 'Id',
                sum((age<18) and (Gender='M')) as 'MaleUsersUnder18',
                sum((age>=18 and age<=40) and (Gender='M')) as 'MaleUsers18To40',
                sum((age>40) and (Gender='M')) as 'MaleUsersOver40',
                sum((age<18) and (Gender='F')) as 'FemaleUsersUnder18',
                sum((age>=18 and age<=40) and (Gender='F')) as 'FemaleUsers18To40',
                sum((age>40) and (Gender='F')) as 'FemaleUsersOver40'
                from User group by Id;

id  MUUnder18  MU18To40  MUOver40  FUUnder18  FU18To40  FUOver40
72      2137     0         1316     645         0         123
79      2613     0         1616     1064        0         676
82      592      0         363      203         0         554

例如,用户表id表示服务站id

Id  userid  Name  age   gender     UserType
72    12     L     18     M        customer

如何修复查询?

pdtvr36n

pdtvr36n1#

最合算的东西

sum(case when age<18 and Gender='M' then 1 else 0 end) as 'MaleUsersUnder18',

等。。

相关问题