sqlsql-server-2008-r2pivotrows

sql repeated date rows to columns on a new table


I'm looking for something similar to the pivot function I have a table that shows date ranges for users, something that tells me that the user was absent between some period of time.

Id UserId BeginingTime EndTime DateApplied
1 63 08:00 10:00 01-01-2017
2 63 10:00 10:40 01-01-2017
3 63 11:00 12:00 03-01-2017
4 63 14:30 15:30 04-01-2017
5 63 13:00 13:30 03-01-2017

I know for a fact that I can only have 2 permissions per day, I need to group the ones that have the same date into a new table.

Data should look something like this

UserId ID1 BeginTime1 EndTime1 ID2 BeginTime2 EndTime2 DateApplied
63 1 08:00 10:00 2 10:00 10:40 01-01-2017
63 3 11:00 12:00 5 13:00 13:30 03-01-2017
63 4 14:30 15:30 null null null 04-01-2017

Solution

  • Since you know you are going to group at most 2 records per user per day, you can simply use a CTE and a left join:

    ;WITH p AS (
      SELECT Id, UserId, BeginingTime, EndTime, DateApplied, 
             ROW_NUMBER() OVER (PARTITION BY UserId, DateApplied ORDER BY BeginingTime) AS RowNo
      FROM SourceTable
    )
    SELECT p1.UserId, p1.Id as ID1, 
           p1.BeginingTime AS BeginingTime1, p1.EndTime AS EndTime1,
           p2.Id as ID2, 
           p2.BeginingTime AS BeginingTime2, p2.EndTime AS EndTime2,
           p1.DateApplied
    FROM p p1 LEFT JOIN p p2 
              ON p1.UserId = p2.UserId AND p1.DateApplied = p2.DateApplied AND p2.RowNo = 2
    WHERE p1.RowNo = 1