--說明:個人學習筆記,實現小計合計顯示,分組按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.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
--*/