Subtotal, sum, and sorting using SQL

Source: Internet
Author: User

-- 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
--*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.