-- Note: personal study notes are displayed in the ascending order of BANK_ID + OP_DATE.
Copy codeThe Code is as follows:
-- Test Data
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 '20180101', '001', '20180101', 1111
Union all select '20180101', '002', '20180101', 2222
Union all select '20180101', '001', '20180101', 3333
Union all select '20180101', '002', '20180101', 4444
Union all select '20180101', '001', '20180101', 5555
Union all select '20180101', '002', '20180101', 6666
GO
-- Query
Select a. ID
, A. BANK_ID
, A. AMT
, B. OP_DATE
, B. OPERATOR_NO
FROM
(
(SELECT
ID = CASE
When grouping (BANK_ID) = 1 THEN 'Total'
When grouping (ID) = 1 THEN 'subtotal'
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 -- calculate the table statistics first, and then add the data in the table above.
SELECT ID
, BANK_ID
, AMT
, ORDER_SIGN1 = 0, ORDER_SIGN2 = BANK_ID
, ORDER_SIGN3 = 0
FROM # TB)
Left join -- to display 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
-- Delete test
Drop table # TB
/*-- Test Result
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
Subtotal 00001 661.00 NULL
4444 002 330.00 20121110 1234567
6666 002 150.00 20121112 1234567
2222 002 222.00 20121210 1234567
Subtotal 002 702.00 NULL
Total NULL 1363.00 NULL
--*/