多列条件聚合
Multi-column Conditional Aggregation
在 SQL Server 2008 中。
我有些东西的组件处于两种状态之一,table 看起来像这样:
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
我用来执行此操作的 'obvious' 查询:
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
表达式的子查询来获取总计、红色、蓝色项目的计数,而是直接使用 CASE
表达式 在聚合函数内部,在本例中为 COUNT
。
也可以使用 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;
在 SQL Server 2008 中。
我有些东西的组件处于两种状态之一,table 看起来像这样:
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
我用来执行此操作的 'obvious' 查询:
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
表达式的子查询来获取总计、红色、蓝色项目的计数,而是直接使用 CASE
表达式 在聚合函数内部,在本例中为 COUNT
。
也可以使用 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;