赞
踩
例子数据是这样的
ID STATUS TYPE
1 0 'A'
2 1 'A'
3 0 'A'
4 1 'B'
5 1 'B'
6 0 'B'
要求是统计每个分类下面的记录条数,以及每个分类下面有效(status=1)的记录条数
汇总列表字段要求
TYPE, 分类总记录数,分类记录有效数
---------------------------------------------------------------
下面是我的实现方法,想问一下有没有其他省力的方法
方法一:
WITH TMP AS(SELECT 1 ID,0 STATUS,'A' TYPE FROM DUAL UNION ALL
SELECT 2,1,'A' FROM DUAL UNION ALL
SELECT 3,0,'A' FROM DUAL UNION ALL
SELECT 4,1,'B' FROM DUAL UNION ALL
SELECT 5,1,'B' FROM DUAL UNION ALL
SELECT 6,0,'B' FROM DUAL)
SELECT TYPE,SUM(1) 记录总数,SUM(CASE WHEN STATUS=0 THEN 0 ELSE 1 END)记录有效数
FROM TMP GROUP BY TYPE;
方法二:
WITH TMP AS(SELECT 1 ID,0 STATUS,'A' TYPE FROM DUAL UNION ALL
SELECT 2,1,'A' FROM DUAL UNION ALL
SELECT 3,0,'A' FROM DUAL UNION ALL
SELECT 4,1,'B' FROM DUAL UNION ALL
SELECT 5,1,'B' FROM DUAL UNION ALL
SELECT 6,0,'B' FROM DUAL),
TMP2 AS(SELECT NVL(STATUS,3) S,TYPE,COUNT(ID) CNT FROM TMP GROUP BY CUBE(P,T)),
TMP3 AS(SELECT * FROM TMP2 PIVOT(MAX(CNT) FOR S IN(3 AS ZS,0 AS WX,1 AS YX)))
SELECT TYPE,ZS,YX FROM TMP3 WHERE P IS NOT NULL;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。