I'm using pgAdmin III / PostgreSQL 9.4 to store and work with my data. Sample of my current data:
x | y
--+--
0 | 1
1 | 1
2 | 1
5 | 2
5 | 2
2 | 2
4 | 3
6 | 3
2 | 3
How I'd like it to be formatted:
1, 2, 3
-- column names are unique y
values
0, 5, 4
-- the first respective x
values
1, 5, 6
-- the second respective x
values
2, 2, 2
-- etc.
It would need to be dynamic because I have millions of rows and thousands of unique values for y
.
Is using a dynamic pivot approach correct for this? I have not been able to successfully implement this:
DECLARE @columns VARCHAR(8000)
SELECT @columns = COALESCE(@columns + ',[' + cast(y as varchar) + ']',
'[' + cast(y as varchar)+ ']')
FROM tableName
GROUP BY y
DECLARE @query VARCHAR(8000)
SET @query = '
SELECT x
FROM tableName
PIVOT
(
MAX(x)
FOR [y]
IN (' + @columns + ')
)
AS p'
EXECUTE(@query)
It is stopping on the first line and giving the error:
syntax error at or near "@"
All dynamic pivot examples I've seen use this, so I'm not sure what I've done wrong. Any help is appreciated. Thank you for your time.
**Note: It is important for the x
values to be stored in the correct order, as sequence matters. I can add another column to indicate sequential order if necessary.