当前位置: 首页 > web >正文

count() + case when统计问题

        在使用sql中统计数据中,因为要统计各个数量的数据,所以在count中使用case when。        

                ​​​​​​​        ​​​​​​​

统计语句如下:

SELECT t.name,count(*)  as total,count(case when status = 1 then 1 else 0 end) as using_count,count(case when status = 0 then 1 else 0 end) as stop_countfrom test_tablel tgroup by t.name

结果统计师有问题的:

测试发现,不管then 和else的返回多少都统计都是类似count(*)一样统计条数。如:

SELECT t.name,count(*)  as total,count(case when status = 1 then 5 else 0 end) as using_count,count(case when status = 0 then 1 else 3 end) as stop_countfrom test_tablel tgroup by t.name

再想到,count(*)是统计条数的,值为0是也属于一条数据。但是count()不会统计null数据。所以改为:

SELECT t.name,count(*)  as total,count(case when status = 1 then 1 else null end) as using_count,count(case when status = 0 then 1 else null end) as stop_countfrom test_tablel tgroup by t.name

或者不适用count函数,改为使用sum函数:

SELECT t.name,count(*)  as total,sum(case when status = 1 then 1 else 0 end) as using_count,sum(case when status = 0 then 1 else 0 end) as stop_countfrom test_tablel tgroup by t.name

http://www.xdnf.cn/news/12526.html

相关文章:

  • Next.js+prisma开发二
  • 【LLMs篇】14:扩散语言模型的理论优势与局限性
  • H_Prj06 8088单板机的串口
  • 贝叶斯网络_TomatoSCI分析日记
  • vanna+deepseek+chainlit 实现自然语言转SQL的精度调优
  • 一种全新的非对称加密算法
  • 豪斯多夫距离 (Hausdorff Distance)在机器人轨迹规划中的应用
  • Kubernetes指标实现有效的集群监控和优化
  • 免费批量图片格式转换工具
  • usbutils工具的使用帮助
  • 【时时三省】(C语言基础)局部变量和全局变量
  • CSDN文章下载到本地的完整指南
  • 88.实现查看收藏功能的前端实现
  • 43道Java多线程高频题整理(附答案背诵版)
  • [蓝桥杯]解谜游戏
  • Tongweb配置跳过扫描应用jar的配置指引(by lqw)
  • 大模型如何革新用户价值、内容匹配与ROI预估
  • C语言字符数组初始化的5种方法(附带实例)
  • 鲲鹏麒麟服务器自制Nacos镜像并部署
  • Linux系统:ELF文件的定义与加载以及动静态链接
  • C++——红黑树
  • 三类 Telegram 账号的风控差异分析与使用建议
  • GWO-LSSVM-Adaboost灰狼算法GWO优化最小二乘支持向量机LSSVM分类预测!
  • python fbx sdk
  • 更新雅可比矩阵的非线性部分笔记
  • 和芯 SL6341 (内置FLASH) 国产USB 3.0HUB芯片 替代 GL3510 VL817
  • 区块链技术相关
  • mybatis中判断等于字符串的条件怎么写
  • ingress-nginx 开启 Prometheus 监控 + Grafana 查看指标
  • 《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)