Один из возможных подходов, используя GROUP BY
с CASE
и FORMAT () (если вы используете SQL Server 2012 +):
Ввод:
CREATE TABLE #Inventory (
ItemType varchar(10),
Price numeric(10, 2),
OnHand int
)
INSERT INTO #Inventory
(ItemType, Price, OnHand)
VALUES
('Coffee', 1.02, 21),
('Coffee', 1.02, 22),
('Coffee', 1.02, 23),
('Coffee', 1.02, 24),
('Tea', 2.01, 11),
('Tea', 2.01, 12),
('Drink', 3.03, 1),
(NULL, 13.13, 3)
T-SQL:
SELECT
CASE
WHEN ItemType <> 'Coffee' AND ItemType <> 'Tea' THEN NULL
ELSE ItemType
END AS ItemType,
FORMAT(SUM(Price * OnHand), '$0.00') AS Total
FROM #Inventory
GROUP BY
CASE
WHEN ItemType <> 'Coffee' AND ItemType <> 'Tea' THEN NULL
ELSE ItemType
END
Вывод:
ItemType Total
NULL $42,42
Coffee $91,80
Tea $46,23