Select statement of a table SQL 2008
-
18-04-2021 - |
Question
I have a table with 3 columns, representing a matrix:
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
How would I select this table in such a way i get
a1 a2 a3
-------
1 12 4
3 4 4
0 2 2
Is there a way to use pivot or what would be the best approach here?
Solution
SELECT [1] AS a1,
[2] AS a2,
[3] AS a3
FROM T
PIVOT (MAX(val) FOR j IN ([1],[2],[3])) AS P
OTHER TIPS
I know I am a little late to the party, but isn't this closer to what you are looking for:
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
Also, this link discusses generation of columns dynamically.
Good Luck!
Matt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow