可搭配GROUPING使用,區分是否為匯總資料行。
DECLARE @TABLE TABLE (Pname VARCHAR(10), SW VARCHAR(10), Qty SMALLINT) INSERT INTO @TABLE VALUES ('AA','1',50) INSERT INTO @TABLE VALUES ('AA','2',70) INSERT INTO @TABLE VALUES ('AA','2',35) INSERT INTO @TABLE VALUES ('AA','3',36) INSERT INTO @TABLE VALUES ('BB','1',25) INSERT INTO @TABLE VALUES ('BB','2',10) INSERT INTO @TABLE VALUES ('BB','2',20) SELECT Pname,SW,Qty=SUM(Qty),GP=GROUPING(Pname) FROM @TABLE GROUP BY Pname,SW WITH ROLLUP
--查詢結果 Pname SW Qty GP ---------- ---------- ----------- ---- AA 1 50 0 AA 2 105 0 AA 3 36 0 AA NULL 191 0 BB 1 25 0 BB 2 30 0 BB NULL 55 0 NULL NULL 246 1參考自:MSDN-GROUPING (Transact-SQL)