Pick just one from a one-to-many relationship

dotroy

New Member
I have a table full of events. I've been asked to create an aggregate table of sessions; one session may have several events. Sessions are identified by having the same arrival time. e.g. (This is a simplification, I'm not typing out actual timestamps):EventID ArrivalTime StartTime EndTime StaffID1 0945 0950 0955 John2 0945 0955 1000 BarbMight be turned into something like:ArrivalTime StartTime EndTime StaffID0945 0950 1000 ???With use of \[code\]MIN(StartTime)\[/code\] and \[code\]MAX(EndTime)\[/code\] to keep it to a single row.The problem I'm running into, as the question marks above indicate, is getting a single staff ID - which staff member it is doesn't matter too much, but I need someone. If it were just a string, as I've shown above, it could be done with \[code\]MIN(StaffID)\[/code\], but the thing that's doing my head in is that I'm required to look up StaffID in the Staff table and pull out the GUID that's associated with the short code that's in my table. And GUID's don't like functions like \[code\]MIN()\[/code\]. Also, just to make matters worse, it's feasible that the StaffID column in the Events table is \[code\]NULL\[/code\], so I have to stick with left joins or similar.Someone suggested a subquery, but apparently my brain refuses to accept this on a Friday and can't see how to get that to work.As a baseline, here's something along the lines of my current query:\[code\]SELECT NEWID() AS SessionID,e.ArrivalTime,MIN(e.StartTime),MAX(e.EndTime),s.StaffGUIDFROM Events e LEFT JOIN Staff s ON e.StaffID = s.StaffIDGROUP BY e.ArrivalTime, s.StaffGUID\[/code\]The problem is that if two different staff members are in the list, the session will show up twice. Any ideas?
 
Top