E
E
eliasum2020-05-01 13:16:44
Transact SQL
eliasum, 2020-05-01 13:16:44

How to create a new table with one query?

Single column table:

2017-02-01 15:00:43
2017-03-18 10:30:10
2017-12-11 01:21:55
2017-12-11 15:33:03
2017-03-18 10:30:10
2017-02-22 08:40:42
2017-06-06 23:59:40

I need to write one query without procedural components, without xn, temporary tables and window functions, which will make it into a two-column table in such a way that each date is closed by the next date:
2017-02-01 15:00:43 2017-02-22 08:40:42
2017-02-22 08:40:42 2017-03-18 10:30:10
2017-03-18 10:30:10 2017-03-18 10:30:10
2017-03-18 10:30:10 2017-06-06 23:59:40
2017-06-06 23:59:40 2017-12-11 01:21:55
2017-12-11 01:21:55 2017-12-11 15:33:03
2017-12-11 15:33:03 null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2020-05-01
@eliasum

DECLARE @T TABLE ( M DATETIME2(0))
INSERT @T VALUES ('2017-02-01 15:00:43'), 
('2017-03-18 10:30:10'),
('2017-12-11 01:21:55'),
('2017-12-11 15:33:03'),
('2017-03-18 10:30:10'),
('2017-02-22 08:40:42'),
('2017-06-06 23:59:40')

SELECT DISTINCT MB.M AS [Start],
  ( SELECT TOP 1 M FROM @T AS ME WHERE (ME.M > MB.M) ORDER BY ME.M ) AS [End]
  FROM @T AS MB
UNION
SELECT M, M
  FROM @T
  GROUP BY M
  HAVING COUNT(M) > 1
ORDER BY 1, 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question