带有Count的SQL Server Pivot子句
我正在使用Microsoft SQL Server并尝试编写以下查询。我想用枢轴条款来计算美国和俄罗斯在2000年奥运会上的金牌数。但我对这两个国家的产出都是零。我知道我可以使用group by获得所需的结果(请参见下面的打印屏幕)。但是如何使用pivot子句实现这一点呢 请参见以下数据集和输出的打印屏幕带有Count的SQL Server Pivot子句,sql,sql-server,tsql,count,pivot,Sql,Sql Server,Tsql,Count,Pivot,我正在使用Microsoft SQL Server并尝试编写以下查询。我想用枢轴条款来计算美国和俄罗斯在2000年奥运会上的金牌数。但我对这两个国家的产出都是零。我知道我可以使用group by获得所需的结果(请参见下面的打印屏幕)。但是如何使用pivot子句实现这一点呢 请参见以下数据集和输出的打印屏幕 select 'Gold' as total_m, ['USA'] as USA, ['RUS'] as RUS from (select c
select
'Gold' as total_m,
['USA'] as USA, ['RUS'] as RUS
from
(select
country, medal, year
from
summer
where
medal = 'Gold'
and year = 2000
and country in ('USA', 'RUS')) as SourceTable
pivot
(count(medal)
for country in (['USA'],['RUS'])) as PivotTable;
数据集
输出
分组依据
从
pivot
列列表中删除引号
select 'Gold' as total_m, [USA] as USA, [RUS] as RUS
from
(select country, medal, year
from summer
where medal = 'Gold'
and year = 2000
and country in ('USA', 'RUS')) as SourceTable
pivot
(count(medal)
for country in ([USA],[RUS])) as PivotTable;
我发现用条件聚合来表达这一点更简单。这是一种可移植的语法,适用于大多数数据库,与特定于供应商的
pivot
语法相比,它不太复杂:
select mdel,
sum(case when country = 'USA' then 1 else 0 end) as USA,
sum(case when country = 'RUS' then 1 else 0 end) as RUS
from summer
where medal = 'Gold' and year = 2000 and country in ('USA', 'RUS')
group by medal