带计数的 SQL Server 数据透视子句

标签 sql sql-server tsql count pivot

我正在使用 Microsoft SQL Server 并尝试在下面编写以下查询。我想使用 Pivot 子句来计算美国和俄罗斯在 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;

数据集

enter image description here

输出

enter image description here

分组依据

enter image description here

最佳答案

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;

关于带计数的 SQL Server 数据透视子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64266187/

相关文章:

c# - 从具有重复数据的 SQL 结果创建键值对

php - SQL 查询似乎不起作用

mysql - 使用自定义 ORDER BY 数据的 SQL 选择

mysql - SELECT 报告性能提升的数据库非规范化

sql - 如何在一个查询中进行选择和更新?

SQL Server 兼容性产生问题

sql - 使用 FROM 子句更新 Postgres 中的记录

sql-server - SSIS 多播 - 在执行下一个 fork 之前等待一个 fork 完成

sql-server - 需要一个基于集合的解决方案来对行进行分组

SQL:如何像 SELECT TOP @amount 中那样使用 TOP 参数?