根据值将行值拆分为特定的列

时间:2019-05-24 10:11:48

标签: sql sql-server-2012 pivot

我有一个这样的表,实际上可以管理VSTS中的障碍

Team Name   Item ID    Score   Score Label
-------------------------------------------
Team1         1          2     Green
Team1         2          0     Red
Team1         3          1     Amber
Team1         4          2     Green
Team1         5          0     Red
Team2         6          1     Amber
Team2         7          0     Red
Team3         8          2     Green

但是我需要以这种不同的方式呈现

Team Name   Item ID    Score   Green    Amber     Red
------------------------------------------------------
Team1         1          2       1       0         0
Team1         2          0       0       0         1
Team1         3          1       0       1         0
Team1         4          2       1       0         0
Team1         5          0       0       0         1
Team2         6          1       0       1         0
Team2         7          0       0       0         1
Team3         8          2       1       0         0

我相信SQL透视是最好的方法。但是我不是枢轴专家。有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

案例表达可能是最快的解决方案:

    SELECT Team Name, Item ID, Score
    , case when Score Label = 'Green' then 1 else 0 end as 'Green'
    , case when Score Label = 'Amber' then 1 else 0 end as 'Amber'
    , case when Score Label = 'Red' then 1 else 0 end as 'Red'
    from Table