前兩天同事問一個oracle使用grouping完成一個統計報表的功能,這個函數帥呆了。開發分組報表直接一個SQL就搞定。
grouping(columnA)函數的意思:當前行如果是由rollup匯總產生的,那麼columnA這個字段值為1否則為0
元數據:
通過grouping查詢後的數據:
sql:
select decode(grouping(f_line)+grouping(f_workarea),1,'小計',2,'總計',f_workarea) f_workarea, decode(grouping(f_line),1,count(*)||'條',f_line) f_line, sum(f_pagesnumber) sum_pagesnumbers from t_testcount group by rollup (f_workarea,f_line);建表數據:
CREATE TABLE t_testcount ( "F_ID" NUMBER(10,0) , "F_WORKAREA" NVARCHAR2(255) , "F_LINE" NVARCHAR2(255) , "F_REMARK" NVARCHAR2(255), "F_YEAR" VARCHAR2(20 BYTE), "F_PAGESNUMBER" NVARCHAR2(255) ); insert into T_TESTCOUNT (f_id, f_workarea, f_line, f_remark, f_year, f_pagesnumber) values (1, 'a', 'a1', null, '2014', '1'); insert into T_TESTCOUNT (f_id, f_workarea, f_line, f_remark, f_year, f_pagesnumber) values (2, 'a', 'a2', null, '2013', '2'); insert into T_TESTCOUNT (f_id, f_workarea, f_line, f_remark, f_year, f_pagesnumber) values (3, 'a', 'a3', null, '2014', '3'); insert into T_TESTCOUNT (f_id, f_workarea, f_line, f_remark, f_year, f_pagesnumber) values (4, 'b', 'b1', null, '2014', '1');