Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有Count的SQL Server Pivot子句_Sql_Sql Server_Tsql_Count_Pivot - Fatal编程技术网

带有Count的SQL Server 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

我正在使用Microsoft SQL Server并尝试编写以下查询。我想用枢轴条款来计算美国和俄罗斯在2000年奥运会上的金牌数。但我对这两个国家的产出都是零。我知道我可以使用group by获得所需的结果(请参见下面的打印屏幕)。但是如何使用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 '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