gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:52:18 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com