I have a data base that records the attributes of users at certain periods of time. A simplified example:
UserID Year Measure1 Measures2
---------------------------------
1, 2000, 3, 4
1, 2001, 5, 6
What I need to do is collapse multiple rows of data into columns
UserID Measure1_2000 Measure1_2001
-----------------------------------
1, 3, 5
Where the end result is that each row tracks users attributes across time. I would prefer to write this as a function or stored procedure, where the number of years that are collapsed into columns is supplied as an argument, so the table structure has to be generated dynamically.
I could use a big table pivot statement, but then the number of columns would be static, and the code would be messy, because I have to collapse multiple types of data into columns.
I tried using some dynamic sql that would iterate through a while loop, joining a list of user ids against the master table, but it is way, way too slow. Does anybody have any ideas?