【问题标题】:SQL Server Pivot clause with Count带计数的 SQL Server Pivot 子句
【发布时间】:2021-01-23 17:12:42
【问题描述】:

我正在使用 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;

数据集

输出

分组

【问题讨论】:

    标签: sql sql-server tsql count pivot


    【解决方案1】:

    pivot 列列表中删除quotes

    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;
    

    【讨论】:

      【解决方案2】:

      我发现用条件聚合来表达这一点更简单。这是一种可移植的语法,适用于大多数数据库,并且在某种程度上不像供应商特定的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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多