我有一个包含3列的表,代表一个矩阵:
i j val
-------
1 1 1
1 2 12
1 3 4
2 1 3
2 2 4
2 3 4
3 1 0
3 2 2
3 3 2
如何以这样的方式选择此表
a1 a2 a3
-------
1 12 4
3 4 4
0 2 2
有没有办法使用枢轴或什么是最好的方法?
答案 0 :(得分:2)
我知道我参加派对有点晚了,但这不是你想要的更接近:
SELECT [1] as a1, [2] as a2, [3] as a3
FROM
(
SELECT i, j, val
FROM T) AS source
PIVOT
(
MAX(val)
FOR j IN ([1], [2], [3])
) as pvt
此外,this link讨论了动态生成列。
祝你好运!
马特
答案 1 :(得分:1)
SELECT [1] AS a1,
[2] AS a2,
[3] AS a3
FROM T
PIVOT (MAX(val) FOR j IN ([1],[2],[3])) AS P