sql server将行值转换为列

时间:2017-08-07 18:38:09

标签: sql-server

Please click to see image of data来源数据 de val_y x1 val1 x1 val2 x1 val3 x1 val4 x1 val5 x2 val7 x2 val8 x2 val9

我想把它变成

dept val_x1 val_x2 val_x3 val_x4 val_x5 val_x6 val_x7 val_x8 val_x9 x1 val1 val2 val3 val4 val5 null null null null x2 val7 val8 val9 null null null null null

因此,如果我有另一个具有N行的部门,则列val_x1到val_xN将填充来自列val_y的值,而列val_xN + 1到val_x9将为空(假设N <9)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您可以使用以下角色:

Select dept, [1] as Val_x1, [2] as Val_x2, [3] as Val_x3, [4] as Val_x4, [5] as Val_x5 from 
( Select dept, val_y, RowN = Row_Number() over (partition by dept order by val_y) from #data1 ) a
pivot (max(val_y) for RowN in([1],[2],[3],[4],[5] --...yourlist of columns
)) p

输出如下:

+------+--------+--------+--------+--------+--------+
| dept | Val_x1 | Val_x2 | Val_x3 | Val_x4 | Val_x5 |
+------+--------+--------+--------+--------+--------+
| x1   | val1   | val2   | val3   | val4   | val5   |
| x2   | val7   | val8   | val9   | NULL   | NULL   |
+------+--------+--------+--------+--------+--------+