Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Pivot clause with Count

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

enter image description here

Output

enter image description here

Group by

enter image description here

like image 565
Darko86 Avatar asked Dec 10 '25 02:12

Darko86


1 Answers

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;
like image 195
Sujitmohanty30 Avatar answered Dec 11 '25 20:12

Sujitmohanty30



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!