--说明: 个人学习笔记,实现小计合计显示,分组按BANK_ID+OP_DATE升序排序 复制代码 代码如下: --测试数据 CREATE TABLE #TB(ID VARCHAR(10),BANK_ID VARCHAR(10),OP_DATE VARCHAR(10),OPERATOR_NO VARCHAR(20),AMT D
--说明:个人学习笔记,实现小计合计显示,分组按BANK_ID+OP_DATE升序排序复制代码 代码如下:--测试数据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.00UNION ALL SELECT '2222','002','20121210',1234567,222.00UNION ALL SELECT '3333','001','20121112',1234567,250.00UNION ALL SELECT '4444','002','20121110',1234567,330.00UNION ALL SELECT '5555','001','20121210',1234567,300.00UNION ALL SELECT '6666','002','20121112',1234567,150.00GO
--查询SELECT A.ID ,A.BANK_ID ,A.AMT ,B.OP_DATE ,B.OPERATOR_NOFROM((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 #TBGROUP BY BANK_ID,ID WITH ROLLUPHAVING GROUPING(ID)=1UNION ALL --先得出表的统计,再加上表中的数据SELECT ID ,BANK_ID ,AMT ,ORDER_SIGN1=0,ORDER_SIGN2=BANK_ID ,ORDER_SIGN3=0 FROM #TB) ALEFT 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_NO3333 001 250.00 20121112 12345675555 001 300.00 20121210 12345671111 001 111.00 20121210 1234567小计 001 661.00 NULL NULL4444 002 330.00 20121110 12345676666 002 150.00 20121112 12345672222 002 222.00 20121210 1234567小计 002 702.00 NULL NULL合计 NULL 1363.00 NULL NULL--*/