Search code examples
sqlsql-servert-sqlstring-aggregation

SQL Query multiple users who started on the same date


I've got a table something like this:

UserID  TeamID  StartedDate
36202   1213    27/11/2019 9:00
36203   1213    1/11/2019 10:30
36203   1207    24/11/2019 10:00
36205   1207    21/11/2019 9:15
36203   1213    1/11/2019 10:30
36214   1217    10/11/2019 10:00
36205   1207    24/11/2019 10:00
36202   1213    1/11/2019 10:30

How do I query a list of users who have the same "StartedDate" for each unique date?

Output should be look like this.

StartedDate         UserID's
24/11/2019 10:00    36203 & 36205
1/11/2019 10:30     36202 & 36203

I need to ignore time & focus on the date only.


Solution

  • You can achieve it by this way, Live demo here

    SELECT DISTINCT C2.StartedDate, 
    SUBSTRING(
    (
       SELECT ', ' + CAST(C1.UserID AS VARCHAR(20))
       FROM TempTable C1
       WHERE C1.StartedDate = C2.StartedDate
      ORDER BY C1.StartedDate
      FOR XML PATH ('')
    ), 2, 1000) AS "UserList"
    FROM TempTable C2
    

    Output

    StartedDate          UserList
    1/11/2019 10:30      36203, 36203, 36202
    10/11/2019 10:00     36214
    21/11/2019 9:15      36205
    24/11/2019 10:00     36203, 36205
    27/11/2019 9:00      36202