如何使用sql查询转换行中的列?

时间:2017-07-05 06:16:50

标签: mysql sql

我使用此查询后得到以下结果:

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

我希望它采用以下格式:

SCHOOL_YEAR   Piano     Violin

2011           100        50
2012           70         150

我怎样才能实现它?

1 个答案:

答案 0 :(得分:0)

在原始表上使用数据透视查询,但仅在学年汇总:

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