mysql 报表 小计 合计_使用SQL实现小计,合计以及排序

Dear 丶 2022-10-27 02:40 381阅读 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

--*/

发表评论

表情:
评论列表 (有 0 条评论,381人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MySQL负数合计

    通过使用MySQL的聚合函数和条件表达式,我们可以很方便地计算负数的合计。在实际应用中,你可以根据自己的需求使用这种方法来计算更复杂的数据合计。如果计算顺序不正确,可能会...

    相关 input标签

    在使用form提交表单的时候,后台得不到一个表单项的数据,很是纳闷,最后经过对比发现, 在提交表单的时候,<input id=" aa" name="bb" type="te