ORACLE分组统计

ORACLE分组统计

ORACLE统计

分组统计就是:按照某种条件,用某种聚合函数统计
一般用到的分组统计有三种

grouping sets:
可以分多组需要分组的值 , 该函数里面的多组分组列,和 grou by grou1 union grou by grou2 效 果一样.
如:
select a,b,c,d,sum(e)
from dept
group by grouping sets((a,b),(c,d));
等效于:
select *
from ( select a,b, c, d,sum(e)
from dept
group by a,b
union
select a, b,c,d,sum(e)
from dept
group by c,d );
实战: 小计:T_DEPT 和 T_PROJECT 的 T_AMOUNT 合计: T_DEPT 的 T_AMOUNT
实现原理,将细分的类型分个组,然后将大类再分一个组。
细类就是名义上的小计,大类就是合计了
先将 T_DEPT 和 T_PROJECT group by ,再 sum(T_AMOUNT) 然后将 T_DEPT group by ,再 sum(T_AMOUNT)

create table TE ( ID T_CODE T_NAME VARCHAR2(2), VARCHAR2(4), VARCHAR2(4), T_AMOUNT INTEGER, T_DEPT VARCHAR2(4), T_PROJECT VARCHAR2(4), T_TYPE );

INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘1’, ‘1’, ‘1’, 10, ‘总部’, ‘90’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘2’, ‘2’, ‘2’, 20, ‘总部’, ‘70’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘3’, ‘3’, ‘3’, 30, ‘分 1’, ‘60’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘4’, ‘4’, ‘4’, 40, ‘分 1’, ‘50’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘5’, ‘5’, ‘5’, 50, ‘分 2’, ‘40’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘7’, ‘7’, ‘7’, 40, ‘分 2’, ‘40’, ‘0’);
INSERT INTO TE
(ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
VALUES
(‘6’, ‘6’, ‘6’, 60, ‘分 2’, ‘30’, ‘0’);

SELECT DECODE(GROUPING(TE.T_PROJECT), 0, TE.T_DEPT, ‘’),
CASE
WHEN GROUPING(TE.T_PROJECT) = 1 AND GROUPING(TE.T_DEPT) = 1 THEN
‘合计’
WHEN GROUPING(TE.T_PROJECT) = 1 THEN
‘小计’
ELSE
T_PROJECT
END,
SUM(T_AMOUNT)
FROM TE
GROUP BY GROUPING SETS((TE.T_DEPT, TE.T_PROJECT),(TE.T_DEPT))

–效果
ORACLE分组统计_第1张图片
rollup:
ROLLUP(A, B, C)
首先会对(A、B、C)进行 GROUP BY,然后对(A、B)进行 GROUP BY,然后是(A)进行 GROUP BY,最后对全表进行 GROUP BY

SELECT DECODE(GROUPING(TE.T_PROJECT), 0, TE.T_DEPT, ‘’),
CASE
WHEN GROUPING(T_DEPT) = 1 AND GROUPING(T_PROJECT) = 1 THEN
‘合计’
WHEN GROUPING(T_PROJECT) = 1 THEN
‘小计’
ELSE
T_PROJECT
END,
SUM(T_AMOUNT)
FROM TE
GROUP BY ROLLUP(T_DEPT, T_PROJECT)
效果:
ORACLE分组统计_第2张图片

亮点:group by ROLLUP(t_dept, t_project) 先对(t_dept, t_project),然 后对 t_dept 进行分组.
统计不同的年/月/日/部门/组织等的时候,这个函数很有用,因为 用 grouping sets 函数会需要写很多分组模式, 注意:这个参数顺序影响 ORACLE 执行结果
cube:
CUBE(A, B, C)
首先会对(A、 C)进行 GROUP BY, B、 然后依次是(A、 B),(A、C),(A),(B、C),(B),©,最后对全表进行 GROUP BY

SELECT T_PROJECT,
CASE
WHEN GROUPING(T_DEPT) = 1 AND GROUPING(T_PROJECT) = 1 THEN
‘合计:’
WHEN GROUPING(T_DEPT) = 1 THEN
T_PROJECT || ‘项目合计:’
WHEN GROUPING(T_PROJECT) = 1 THEN
T_DEPT || ‘部门合计:’
ELSE
T_DEPT
END,
SUM(T_AMOUNT)
FROM TE
GROUP BY CUBE(T_DEPT, T_PROJECT)
ORDER BY T_PROJECT, T_DEPT
ORACLE分组统计_第3张图片
[摘抄某位道友,若有冒犯,多有得罪]

你可能感兴趣的:(oracle)