[英]Multi-column Conditional Aggregation
在SQL Server 2008中。
我有在兩種狀態之一中具有組件的事物,該表如下所示:
create table Things (
ThingName varchar(10),
ItemNumber INT,
ItemStatus varchar(10));
INSERT INTO Things (
ThingName,
ItemNumber,
ItemStatus)
VALUES
('a', 1, 'red'),
('a', 2, 'red'),
('a', 3, 'blue'),
('b', 1, 'red'),
('b', 2, 'red'),
('b', 3, 'red'),
('b', 4, 'red'),
('c', 1, 'blue'),
('c', 2, 'blue'),
('c', 3, 'red');
我需要的結果是1)項目總數2)紅色項目總數3)藍色項目總數
結果如下所示:
ThingName TotalItems RedItems BlueItems
a 3 2 1
b 4 4 0
c 3 1 2
我用來執行此操作的“顯而易見”查詢:
SELECT
ThingName,
sum(Red + Blue) as TotalItems,
sum(Red) as RedItems,
sum(Blue) as BlueItems
FROM (
SELECT
ThingName,
case
when ItemStatus = 'red' then count(*)
else 0
end as Red,
case
when ItemStatus = 'blue' then count(*)
else 0
end as Blue
FROM Things
GROUP BY
ThingName,
ItemStatus) a GROUP BY ThingName;
這可行,但看起來很原始,令人不滿意。 實際上,好像我沒看到如何根據需要進行匯總而不采用兩步方法。 有什么建議嗎?
您可以使用條件聚合來簡化事情:
SELECT
ThingName,
count(ItemNumber) as TotalItems,
count(case when ItemStatus='Red' then ItemNumber end) as RedItems,
count(case when ItemStatus='Blue' then ItemNumber end) as BlueItems
FROM Things
GROUP BY ThingName;
因此,不要使用使用CASE
表達式的子查詢來獲取Total,Red,Blue項目的計數,而是直接在聚合函數(在本例中為COUNT
內使用CASE
表達式。
sum
也可以:
SELECT
ThingName,
COUNT(*) as TotalItems,
SUM(CASE ItemStatus WHEN 'Red' THEN 1 ELSE 0 END) AS RedItems,
SUM(CASE ItemStatus WHEN 'Blue' THEN 1 ELSE 0 END) AS BlueItems
FROM Things
GROUP BY ThingName;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.