SQL将行转换为具有唯一列名

时间:2016-12-20 17:45:19

标签: sql-server

我有以下数据:

Id  RaceId  Position    Letter_v_Letter Number  Letter  Letter_Number
1   1       1           H-C HARD        5       C HARD  C HARD5
2   1       2           J-D             3       D       D3
3   1       3           D               8       D       D8

我需要为Letter_v_Letter,Number,Letter和Letter_Number中的每一行返回单行[RaceId],其中包含第1列到第3列

我一直在看枢轴,联合所有并在这里交叉应用示例但是无法得到我需要的结果:

RaceId    Letter_v_Letter_1  Letter_v_Letter_2  Letter_v_Letter_3  Number_1  Number_2  etc.
1         H-C Hard           J-D                D                  5         3

我正在使用它来创建2个表中的视图以简化查找查询

它会成为临时工作台吗?

1 个答案:

答案 0 :(得分:2)

条件聚合可以解决这个问题

Select RaceID
      ,Letter_v_Letter_1 = max(case when Position=1 then Letter_v_Letter end)
      ,Letter_v_Letter_2 = max(case when Position=2 then Letter_v_Letter end)
      ,Letter_v_Letter_3 = max(case when Position=3 then Letter_v_Letter end)
      ,Number_1          = max(case when Position=1 then Number end)
      ,Number_2          = max(case when Position=2 then Number end)
      ,Number_3          = max(case when Position=3 then Number end)
      ,Letter_1          = max(case when Position=1 then Letter end)
      ,Letter_2          = max(case when Position=2 then Letter end)
      ,Letter_3          = max(case when Position=3 then Letter end)
      ,Letter_Number_1   = max(case when Position=1 then Letter_Number end)
      ,Letter_Number_2   = max(case when Position=2 then Letter_Number end)
      ,Letter_Number_3   = max(case when Position=3 then Letter_Number end)
 From  YourTable
 Group By RaceID

返回

enter image description here