自 SQL Server 2012 中不推荐使用Compute By 以来,RollUp 的一种 hack - (请参阅“SQL SERVER – 使用 ROLL UP 子句而不是 COMPUTE BY”)
DECLARE @t TABLE(AccountNumber VARCHAR(10),[Description] VARCHAR(100),ShortDescription VARCHAR(100),Balance INT)
INSERT INTO @t SELECT '1234567890','Some Description for 1st Account','Short Description for 1st Account',2000 Union All
SELECT '2345678901','Some Description for 2nd Account','Short Description for 2nd Account',3000 Union All
SELECT '1234567890','Some Description for 1st Account','Short Description for 1st Account',4000
SELECT
AccountNumber
,Balance
,Total = SUM(Balance)
FROM @t
GROUP BY AccountNumber,Balance
WITH ROLLUP
结果
AccountNumber Balance total
1234567890 2000 2000
1234567890 4000 4000
1234567890 NULL 6000
2345678901 3000 3000
2345678901 NULL 3000
NULL NULL 9000
或者
你可以使用下面的
DECLARE @t TABLE(AccountNumber VARCHAR(10),[Description] VARCHAR(100),ShortDescription VARCHAR(100),Balance INT)
INSERT INTO @t SELECT '1234567890','Some Description for 1st Account','Short Description for 1st Account',2000 Union All
SELECT '2345678901','Some Description for 2nd Account','Short Description for 2nd Account',3000 Union All
SELECT '1234567890','Some Description for 1st Account','Short Description for 1st Account',4000
;With CTE AS
(
SELECT
AccountNumber
,[Description]
,ShortDescription
,Balance
,SubTotal = SUM(Balance) OVER (PARTITION BY AccountNumber ORDER BY LEFT (AccountNumber, 2))
,Rn = ROW_NUMBER() OVER(PARTITION BY AccountNumber ORDER BY LEFT (AccountNumber, 2))
FROM @t)
SELECT
AccountNumber
,[Description]
,ShortDescription
,Balance = CAST(Balance AS VARCHAR(10))
,SubTotal = CASE WHEN Rn != 1 THEN NULL ELSE SubTotal END
FROM CTE
UNION ALL
SELECT
' ', ' ',' ' ,'Total Amount' , SUM(Balance) FROM CTE
输出是
AccountNumber Description ShortDescription Balance SubTotal
1234567890 Some Description for 1st Account Short Description for 1st Account 2000 6000
1234567890 Some Description for 1st Account Short Description for 1st Account 4000 NULL
2345678901 Some Description for 2nd Account Short Description for 2nd Account 3000 3000
Total Amount 9000