日期:2014-05-16  浏览次数:20599 次

oracle分组小计,总计样例(grouping sets)
1.首先创建一个表
create table TE
(
  ID        VARCHAR2(2),
  T_CODE    VARCHAR2(4),
  T_NAME    VARCHAR2(4),
  T_AMOUNT  INTEGER,
  T_DEPT    VARCHAR2(4),
  T_PROJECT VARCHAR2(4),
  T_TYPE    VARCHAR2(1)
)


2.录入数据如下:
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 ('6', '6', '6', 60, '分2', '30', '0');


3.查询全表查看
select * from te;





4.用t.t_dept, t.t_project进行分组查询

select t.t_dept, t.t_project, sum(t.t_amount) from te t
group by t.t_dept, t.t_project;


结果如下:



5.用t.t_dept, t.t_project,并使用t.t_dept来做小计

select t.t_dept, t.t_project, sum(t.t_amount) from te t
group by grouping sets ((t.t_dept, t.t_project), t.t_dept);


结果如下:




6.用t.t_dept, t.t_project,并使用t.t_dept来做小计,并做一次总计

select t.t_dept, t.t_project, sum(t.t_amount) from te t
group by grouping sets ((t.t_dept, t.t_project), t.t_dept, null);


结果如下:






7.使用grouping(字段)

select grouping(t.t_dept),t.t_dept, t.t_project, sum(t.t_amount) from te t
group by grouping sets ((t.t_dept, t.t_project), t.t_dept, null);



结果如下:






insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('1', '1', '1', 10, '总部', '90', '1');

insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('2', '2', '2', 20, '总部', '70', '1');

insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('3', '3', '3', 30, '分1', '60', '1');

insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('4', '4', '4', 40, '分1', '50', '1');

insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('5', '5', '5', 50, '分2', '40', '1');

insert into te (ID, T_CODE, T_NAME, T_AMOUNT, T_DEPT, T_PROJECT, T_TYPE)
values ('6', '6', '6', 60, '分2', '30', '1');



select grouping(t.t_dept),t.t_dept, t.t_project, t.t_type, sum(t.t_amount) from te t
group by grouping sets ((t.t_dept, t.t_project,t.t_type), (t.t_dept,t.t_project),t.t_dept, null);







注意: 在存储过程中null不会正确执行 需要改成()


select grouping(t.t_dept),t.t_dept, t.t_project, t.t_type, sum(t.t_amount) from te t
group by grouping sets ((t.t_dept, t.t_project,t.t_type), (t.t_dept,t.t_project),t.t_dept, ());


完!