时间:2021-12-08 13:18:01 | 栏目:Mysql | 点击:次
--说明:个人学习笔记,实现小计合计显示,分组按BANK_ID+OP_DATE升序排序
--查询
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
--*/