请参阅 使用 ROLLUP 在 SQL 中聚合数据
执行:
DECLARE @SOMETABLE TABLE (SUBMARKETER INT, GRADE CHAR, MARKETER INT,
DATE DATETIME, TOTAL INT)
INSERT INTO @SOMETABLE
SELECT 1415, 'A', 22, '02/25/2009', 26 UNION
SELECT 1415, 'B', 22, '02/25/2009', 93 UNION
SELECT 1415, 'C', 22, '02/25/2009', 1175 UNION
SELECT 1415, 'D', 22, '02/25/2009', 510 UNION
SELECT 1169, 'B', 500, '02/25/2009', 1 UNION
SELECT 1169, 'C', 500, '02/25/2009', 3 UNION
SELECT 1393, 'C', 500, '02/25/2009', 2 UNION
SELECT 2, 'B', 500, '02/25/2009', 5 UNION
SELECT 2, 'C', 500, '02/25/2009', 111 UNION
SELECT 2, 'D', 500, '02/25/2009', 18
SELECT
CASE WHEN SUBMARKETER IS NULL THEN 'Marketer Total'
ELSE CONVERT(VARCHAR, MARKETER) END MARKETER,
SUBMARKETER, GRADE, TOTAL, DATE
FROM (
SELECT MARKETER, SUBMARKETER, GRADE, SUM(TOTAL) AS TOTAL,
CONVERT(VARCHAR,DATE,101)[DATE]
FROM @SOMETABLE
WHERE DATE >= '2/25/2009' AND DATE < '2/26/2009'
AND MARKETER IN ('22','500')
GROUP BY MARKETER, SUBMARKETER, GRADE, DATE WITH ROLLUP
)M
WHERE M.MARKETER IS NOT NULL
AND NOT (SUBMARKETER IS NOT NULL AND DATE IS NULL)
注意:如果 MARKETER、SUBMARKETER 和 DATE 列不为空,这将正常工作。如果表中这些字段的值为NULL,那么过滤掉无用的分组将成为一个问题。