善用sql语句之case when 条件 then X else X end

16 篇文章 0 订阅
8 篇文章 0 订阅

总结一个常用的通知数据的sql

原型展示

在这里插入图片描述
这里的数据展示, 需要将数据库中的数据按照不同条件统计并返回给前端
有一下几种方案
方案 一:
上方展示的每个数据都写一条sql, 书写简单, 但是比较费事, 重复劳动 。这里不做展示

方案 二:
利用子查询,将多条sql写在一个大sql中, 其实本质上依然是多条sql, 而且子查询多了, 数据库查询效率也会比较慢, 这在数据量大的时候, 尤为明显, 子查询代码如下

select
        (select count(cu.id) from cloud_user cu where cu.userType=3 ) as partner_count,
        (select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state !=2 ) as not_car_owner_partner_count,
        (select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state = 2 ) as car_owner_partner_count,
        (select count(cu.id) from cloud_user cu where cu.userType=3 and cu.state = 4 ) as stopPartnerCount
        from cloud_user cu

方案 三:
利用case when , 代码如下

<select id="getPartnerStatistics" resultType="com.etouch.pojo.dto.minipro.CloudUserDataDTO">
        select
        sum(case when cu.userType=3 then 1 else 0 end ) as partner_count,
        sum(case when cu.userType=3 and cu.state !=2 then 1 else 0 end ) as not_car_owner_partner_count,
        sum(case when cu.userType=3 and cu.state = 2 then 1 else 0 end ) as car_owner_partner_count,
        sum(case when cu.userType=3 and cu.state = 4 then 1 else 0 end ) as stopPartnerCount
        from cloud_user cu
        where <include refid="searchCloudUserData"/>
    </select>

case when 条件成立时, 会运行then 后面的, 也就是取1, 不成立则 运行 else 后面的, 取 0, 最后一定要加上end, 否则, 运行会报错

查询结果如下

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

意田天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值