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 ?

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

5 Comments

That would count the rows for each "music", instead of "THEN 1" it should be music.
@SloanThrasher The MUSIC column is text, not a number, read the question. The only issue here would be counting NULL values. My summation would ignore NULL, as would the COUNT() function.
@TimBiegeleisen : I think instead of 1 and 0 should use ct.
@TimBiegeleisen: You are right, my mistake. It should be ct and 0.
@Wanderer The original table has no such column called ct. Read the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.