4

I'm having a trouble of creating a list of dates given with a two or more different items. Here's what my data looks like

RAW DATA
ID| Start Date Time     | End Date Time
1 | 2018-08-06 13:00:00.000 | 2018-08-07 10:00:00.000
2 | 2018-08-10 08:00:00.000 | 2018-08-10 15:00:00.000

RESULT
ID| Start Date Time     | End Date Time
1 | 2018-08-06 13:00:00.000 | 2018-08-06 23:59:59.000
1 | 2018-08-07 00:00:01.000 | 2018-08-07 10:00:00.000
2 | 2018-08-10 08:00:00.000 | 2018-08-10 15:00:00.000

Is this possible? Thanks

0

1 Answer 1

3

You can try to use CTE recursion to make it.

The keypoint is, let startTime column add one day then convert DateTime to Date in the CTE recursion condition.

CREATE TABLE T(
  ID INT,
  [Start Date Time] DATETIME,
  [End Date Time] DATETIME
);
INSERT INTO T VALUES (1,'2018-08-06 13:00:00.000','2018-08-07 10:00:00.000');
INSERT INTO T VALUES (2,'2018-08-10 08:00:00.000','2018-08-10 15:00:00.000');

Query 1:

;WITH CTE AS (
    SELECT ID,[Start Date Time] startTime,[End Date Time] endTime
    FROM T
    UNION ALL
    SELECT ID,CAST(CAST(DATEADD(DAY,1,startTime)AS DATE) AS DATETIME),endTime 
    FROM CTE
    WHERE CAST(CAST(DATEADD(DAY,1,startTime) AS DATE) AS DATETIME) < endTime
)
SELECT id,
       startTime AS 'Start Date Time',
       (CASE WHEN LEAD(startTime,1,endTime) OVER(PARTITION BY ID ORDER BY startTime)= endTime 
                 THEN endTime
                 ELSE DATEADD(second,-1,LEAD(startTime,1,endTime) OVER(PARTITION BY ID ORDER BY startTime)) 
            END) AS 'End Date Time' 
FROM CTE

Results:

| id |      Start Date Time |        End Date Time |
|----|----------------------|----------------------|
|  1 | 2018-08-06T13:00:00Z | 2018-08-06T23:59:59Z |
|  1 | 2018-08-07T00:00:00Z | 2018-08-07T10:00:00Z |
|  2 | 2018-08-10T08:00:00Z | 2018-08-10T15:00:00Z |
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.