1、创建表
desc test_rollup; Name Type Nullable Default Comments ----------- ------------ -------- ------- -------- TYPE_NAME VARCHAR2(10) Y TYPE_VALUE NUMBER Y TYPE_NAME2 VARCHAR2(10) Y TYPE_VALUE2 NUMBER Y
2、插入数据
select * from test_rollup; TYPE_NAME TYPE_VALUE TYPE_NAME2 TYPE_VALUE2 ---------- ---------- ---------- ----------- a 123 t1 120 a 423 t2 200 a 523 t1 555 b 223 x1 504 b 283 x2 484 c 103 y1 333 c 843 y2 984 c 899 y2 151 c 100 y2 150 d 204 s1 606 10 rows selected
3、使用grouping_id查询结果
select type_name, type_name2, decode(grouping_id(type_name), 0, type_name, '总计')g_type, decode(grouping_id(type_name2), 0, type_name2, decode(grouping_id(type_name),0,'小计','总计'))g2_type, grouping_id(type_name, type_name2)gg_type, sum(type_value), sum(type_value2) from test_rollup group by rollup(type_name, type_name2); TYPE_NAME TYPE_NAME2 G_TYPE G2_TYPE GG_TYPE SUM(TYPE_VALUE) SUM(TYPE_VALUE2) ---------- ---------- ---------- ---------- ---------- --------------- ---------------- a t1 a t1 0 646 675 a t2 a t2 0 423 200 a a 小计 1 1069 875 b x1 b x1 0 223 504 b x2 b x2 0 283 484 b b 小计 1 506 988 c y1 c y1 0 103 333 c y2 c y2 0 1842 1285 c c 小计 1 1945 1618 d s1 d s1 0 204 606 d d 小计 1 204 606 总计 总计 3 3724 4087 12 rows selected