看到Using ROLLUP to aggregate data in 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)
注意:這將正常工作,如果營銷商,SUBMARKETER和日期欄,NOT NULL。如果表中有這些字段的NULL值,那麼這將成爲濾除無用分組的問題。
提供的表結構和當前選擇查詢 – 2009-02-26 21:38:56