I'm using Microsoft SQL Server and trying to write the following query below. I want to use the Pivot clause to get the count in gold medals for USA and Russia from the Olympics 2000. But My output is Zero for both countries. I know that I can use the group by to get the desired result (see print screen below). But how can do this with the pivot clause?
Please see print screens of the dataset and the output below
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;
Dataset

Output

Group by

Remove quotes from pivot column list,
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With