0

I have the following result which i have got after using this query :

select SCHOOL_YEAR,COUNT(MUSIC) as ct,MUSIC from [table1]
group by SCHOOL_YEAR,MUSIC;

SCHOOL_YEAR   ct      MUSIC

2011          100     Piano
2011          50      Violin
2012          70      Piano
2012          150     Violin

I want it in the following format :

SCHOOL_YEAR   Piano     Violin

2011           100        50
2012           70         150

How can i achieve it ?

goonerboi
  • 309
  • 6
  • 18
  • Please check the transpose in sql https://stackoverflow.com/questions/10699997/sql-server-transpose-rows-into-columns[enter link description here](https://stackoverflow.com/questions/10699997/sql-server-transpose-rows-into-columns) – zen Jul 05 '17 at 06:21

1 Answers1

0

Use a pivot query on the original table, but aggregate only on the school year:

SELECT
    SCHOOL_YEAR,
    SUM(CASE WHEN MUSIC = 'Piano'  THEN 1 ELSE 0 END) AS Piano,
    SUM(CASE WHEN MUSIC = 'Violin' THEN 1 ELSE 0 END) AS Violin
FROM table1
GROUP BY
    SCHOOL_YEAR
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360