4

DB2查询某条件占比的SQL

 3 years ago
source link: https://www.lujun9972.win/blog/2020/04/20/db2%E6%9F%A5%E8%AF%A2%E6%9F%90%E6%9D%A1%E4%BB%B6%E5%8D%A0%E6%AF%94%E7%9A%84sql/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

DB2查询某条件占比的SQL

今天为晨检脚本增加了记录记账成功率的功能,SQL的写法大致为:

select sum(case when 记账状态='记账成功' then 1 else 0 end)/cast(count(1) as decimal(18,2)) from 表 where 条件

这里有两个关键点:

  1. 使用case语句将符合条件的记录值变为1,其他值变为0,这样累加起来的值就是符合条件的记录数了。
  2. 在DB2中两个整数做除法,结果还会是一个整数。这时需要使用cast语句将其中一个整数转换为小数才能保留小数位。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK