Sql 对同一列进行不同条件统计(条件筛选)
PostgreSql当发现可以进行筛选时,语句如下:SELECTcount(*) filter (where PERIOD = '01')AS business_daily, -- 日累计 业务办理count(*) filter (where PERIOD = '02')AS business_per_month -- 月累计 业务办理FROM`k_id_idx` as kiWHERE idx_c
·
1. PostgreSql
当发现可以进行筛选时,语句如下:
SELECT
count(*) filter (where PERIOD = '01') AS business_daily, -- 日累计 业务办理
count(*) filter (where PERIOD = '02') AS business_per_month -- 月累计 业务办理
FROM
`k_id_idx` as ki
WHERE idx_code = 'GD010'
2. Mysql
可是上面的 count filter 语句并不能使用在 mysql 中,但是 count 函数和 if 函数结合可以达到同样的效果,语句如下:
count() 函数
统计数据表中的行的总数,忽略空值
if(expr, v1, v2) 函数
if(expr, v1, v2) 表达式expr为true (expr<>0 and expr <> NULL) 返回v1,否则v2
SELECT
count(if(PERIOD = '01', pid, null)),
count(DISTINCT if(PERIOD = '02', pid, null)) -- 如果返回字段结果不唯一的话,可加上 DISTINCT 去掉重复字段再统计,这里用 1 来标记的话,不可用 DISTINCT;
FROM `k_id_idx`
WHERE idx_code = '010'
根据原理,可使用 sum 函数加上 if 函数,用 1 来标记累加,效果相同;(用 1 标记,count/sum 不可用 DISTINCT 去重)
SELECT
sum(if(PERIOD = '01', 1, 0)),
sum(if(PERIOD = '02', 1, 0)) -- 如果存在累加 1 ,没有累加 0;
FROM `k_id_idx`
WHERE idx_code = '010'
3. Oracle
- case when 语句:
select
sum(case u.sex when 1 then 1 else 0 end) as '男性',
sum(case u.sex when 2 then 1 else 0 end) as '女性',
sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end) as '性别为空'
from users u;
-- 或者
select
sum(case u.sex when 1 then 1 end) as '男性',
sum(case u.sex when 2 then 1 end) as '女性',
sum(case when u.sex <>1 and u.sex<>2 then 1 end) as '性别为空'
from users u;
- case when 字典替换功能:
select u.id,u.name,
(case u.sex
when 1 then '男'
when 2 then '女'
else '空的'
end
) as '性别'
from users u;
(完)
更多推荐
已为社区贡献8条内容
所有评论(0)