sql之sum case when

假定:有一张user表,里面有字段性别sex(1男2女)、婚姻状态marriageStatus(0未结婚、1已结婚、2离异),现在要按部门(deptid)统计各部门的性别、婚姻状态。如何实现?

最早我是这么做的:

        1、对user表按deptid、sex进行分组统计;

        2、对user表按deptid、marriageStatus进行分组统计;

        3、分页查询部门表

        4、用部门id与1、2的结果对接(要么用sql 的left join),要么用java的map

现在我是这么做的:

        1、分页查询部门表

        2、收集部门id

        3、用部门id做为分组及限制条件,用sum case when 做统计

select depteid,
    sum(case sex when 1 then 1 else 0) as '男性',
    sum(case sex when 2 then 1 else 0) as '女性',
    sum(case marriageStatus when 0 then 1 else 0) as '未婚',
    sum(case marriageStatus when 1 then 1 else 0) as '已婚',
    sum(case marriageStatus when 2 then 1 else 0) as '离异'
from user
 where deptid in (......)
 group by deptid

        4、把3的结果转成id为deptid,value为结果对象的map,遍历1查询出的部门,组装出结果

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值