Friday 18 May 2018

SQL Dynamic Column Query












I have a table of "Events", and each event has a a list of 1-4 (essentially variable #) "Users". So let's say I get all events for today, and then I want to list the users as a dynamic number of columns, rather than repeated rows.



Right now I have



SELECT E.EventID, E.Time, U.Name FROM Events
INNER JOIN Users U ON E.UserID = U.UserID
WHERE Date = '12/20/2010'


This brings me results like:




EventID, Time, Name
211, '4:00am', 'Joe'
211, '4:00am', 'Phil'
211, "4:00am', 'Billy'
218, '7:00am', 'Sally'
218, '7:00am', 'Susan'


I can work with this and it's acceptable, however the duplication for EventID and Time (there are more columns in my actual query) seems wasteful to me. What I would really like in the output is this:




EventID, Time, Name1, Name2, Name3
211, '4:00am', 'Joe', 'Phil', 'Billy'
218, '7:00am', 'Sally', 'Susan', NULL


I have tried looking at tutorials for PIVOTs (I have SQL 2008), but I don't know if they conceptually match what I'm trying to do. Most of them are using "MIN" or "MAX".



Maybe this can't be done? My other alternative is to get a list of Events for today, and then loop through that, finding a recordset of Users for that Event. I would prefer to grab it all in one query though.




Any ideas?


Answer



Returning a variable number of columns would be harder to deal with in code. The result set you are currently getting is easy to transform into an object that you can worth with in code.



What are you trying to do with the output?


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...