Lihat sesuatu seperti
DECLARE @Sales TABLE(
CUS_ID INT,
PRODUCT VARCHAR(20),
AMOUNT FLOAT
)
INSERT INTO @Sales SELECT 12,'A', 2.50
INSERT INTO @Sales SELECT 12,'B', 5.80
INSERT INTO @Sales SELECT 24,'A', 10.00
INSERT INTO @Sales SELECT 24,'B', 30.00
;WITH Vals AS (
SELECT cus_id,
product,
amount,
1 DisplayOrder,
SUM(amount) OVER(PARTITION BY cus_id) OrderTotal
FROM @Sales
UNION ALL
SELECT cus_id,
'Total' AS product,
SUM(amount),
2 DisplayOrder,
SUM(amount)
FROM @Sales
GROUP BY cus_id
)
SELECT cus_id,
product,
amount
FROM Vals
ORDER BY OrderTotal DESC,cus_id,DisplayOrder, product