About me:Oracle ACE pro,optimistic,passionate and harmonious. Focus on ORACLE,MySQL and other database programming,peformance tuning,db design, j2ee,Linux/AIX,Architecture tech,etc
全部博文(172)
分类: Oracle
2022-04-10 21:08:24
create table test_h ( id varchar(50), --和子表ID是匹配的 unit_code varchar(50), --单位编码 input_date varchar(50), --制单日期 account_time varchar(50)--会计日期 ) create table test_b ( vouch_id varchar(50),--和主表ID是匹配的 digest varchar(50), --摘要 amount number,--金额 direct varchar(50),--借贷方向 item_code varchar(50)--项目编码 ) select * from test_h; select * from test_b --主表数据 insert into test_h (ID, UNIT_CODE, INPUT_DATE, ACCOUNT_TIME)values ('id01', '001', '2013-01-02', '2013-01-30'); insert into test_h (ID, UNIT_CODE, INPUT_DATE, ACCOUNT_TIME)values ('id02', '001', '2013-02-02', '2013-01-30'); insert into test_h (ID, UNIT_CODE, INPUT_DATE, ACCOUNT_TIME)values ('id03', '002', '2013-02-02', '2013-01-30'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id01', '摘要1', 10, 'J', '项目a'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id01', '摘要x', 10, 'D', '项目b'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id02', '摘要d', 50, 'J', '项目c'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id02', '摘要f', 50, 'D', '项目d'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id03', '摘要d', 50, 'J', '项目c'); insert into test_b (VOUCH_ID, DIGEST, AMOUNT, DIRECT, ITEM_CODE)values ('id03', '摘要f', 50, 'D', '项目d'); COMMIT; |
--注意grouping_id的使用,这是格式化报表 SELECT decode(grouping_id(a.unit_code,a.id,b.digest,b.item_code),3,'小计',7,'合计',15,'总合计',0,a.unit_code) unit_code, b.digest,b.item_code,sum(decode(b.direct,'J',b.amount)) jprice,sum(decode(b.direct,'D',b.amount)) dprice FROM test_h a,test_b b WHERE a.id=b.vouch_id GROUP BY ROLLUP (a.unit_code,a.id,(b.digest,b.item_code)); |
SQL> SELECT decode(grouping_id(a.id,b.digest,b.item_code),3,'小计',7,'合计',0,a.unit_code) unit_code, 2 b.digest,b.item_code,sum(decode(b.direct,'J',b.amount)) jprice,sum(decode(b.direct,'D',b.amount)) dprice 3 FROM test_h a,test_b b 4 WHERE a.id=b.vouch_id 5 GROUP BY a.unit_code,ROLLUP (a.id,(b.digest,b.item_code)); UNIT_CODE DIGEST ITEM_CODE JPRICE DPRICE -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ---------- ---------- 001 摘要1 项目a 10 001 摘要x 项目b 10 小计 10 10 001 摘要d 项目c 50 001 摘要f 项目d 50 小计 50 50 合计 60 60 002 摘要d 项目c 50 002 摘要f 项目d 50 小计 50 50 合计 50 50 |