Skip to content
Advertisement

SQL query to CONCAT/list unique column data if rows have identical data in the other columns?

Thanks in advance. I’m basically trying to run a SQL query so that the results are 1:1:1:1:Many for StaffID:Name:Floor:Date:Shifts.

Here is my initial query and example results:

I then combined the ShiftStart and ShiftEnd columns with the following to get the further below results:

What I can’t figure out to do next though is to combine Andrew’s shifts (and anyone else’s multiple shifts on the same Date and Floor etc) like the below:

NOTE: If someone is transferred to another Floor (occasional), I want to keep that Shift/s on separate rows unique to the Floor so the Floor data can be split up and emailed to that floor’s manager. As long as all data of the rows are identical except for the Shift, I want to combine those rows and list the Shifts. Thanks again!

Advertisement

Answer

As mentioned, you should use the String_Agg function as follows:

For Sql Server 2012, you can try “CTE” with “FOR XML PATH”.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement