mysql 报表 小计 合计_使用SQL实现小计,合计以及排序 Dear 丶 2022-10-27 02:40 229阅读 0赞 \--测试数据create table \#tb(id varchar(10),bank\_id varchar(10),op\_date varchar(10),operator\_no varchar(20),amt decimal(10,2)) insert \#tb select '1111','001','20121210',1234567,111.00 union all select '2222','002','20121210',1234567,222.00 union all select '3333','001','20121112',1234567,250.00 union all select '4444','002','20121110',1234567,330.00 union all select '5555','001','20121210',1234567,300.00 union all select '6666','002','20121112',1234567,150.00 go \--查询select a.id ,a.bank\_id ,a.amt ,b.op\_date ,b.operator\_no from ( (select id=case when grouping(bank\_id)=1 then '合计' when grouping(id)=1 then '小计' else id end ,bank\_id ,sum(amt) amt ,order\_sign1=grouping(bank\_id),order\_sign2=bank\_id ,order\_sign3=grouping(id) from \#tb group by bank\_id,id with rollup having grouping(id)=1 union all --先得出表的统计,再加上表中的数据 select id ,bank\_id ,amt ,order\_sign1=0,order\_sign2=bank\_id ,order\_sign3=0 from \#tb) a left join --为了显示出op\_date、operator\_no (select id ,op\_date ,operator\_no from \#tb) b on a.id = b.id ) order by order\_sign1,order\_sign2,order\_sign3,op\_date go \--删除测试drop table \#tb /\*--测试结果 id bank\_id amt op\_date operator\_no 3333 001 250.00 20121112 1234567 5555 001 300.00 20121210 1234567 1111 001 111.00 20121210 1234567 小计 001 661.00 null null 4444 002 330.00 20121110 1234567 6666 002 150.00 20121112 1234567 2222 002 222.00 20121210 1234567 小计 002 702.00 null null 合计 null 1363.00 null null \--\*/
还没有评论,来说两句吧...