2017-04-18 63 views
1

我正在尋找類似於主要功能的東西 我有一個表格顯示用戶的日期範圍,它告訴我用戶在一段時間內不在。sql重複日期行到新表上的列

Id | UserId |開始時間| 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

我知道一個事實,即我每天只能擁有2個權限,我需要將具有相同日期的那些分組到新表中。

數據應該看起來像這樣

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 |空| 2017年4月1日

回答

0

既然你知道你要組最多2個記錄每個用戶每天,你可以簡單地用一個CTE和左連接:

;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