I have data like this. Basically date and time.
DECLARE @sample table
(
_date date,
_time Time(0)
)
INSERT INTO @sample
VALUES
('2022-06-22', '09:00:00'),
('2022-06-22', '09:30:00'),
('2022-06-22', '10:00:00'),
('2022-06-22', '10:30:00'),
('2022-06-22', '11:00:00'),
('2022-06-23', '09:00:00'),
('2022-06-23', '09:30:00'),
('2022-06-23', '10:00:00');
And I added row number to it.
WITH cte AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY _date ORDER BY _time) AS rn
FROM @sample
)
SELECT *
FROM cte
After that, the data look like this.
| _date | _time | rn |
|------------|----------|----|
| 2022-06-22 | 09:00:00 | 1 |
| 2022-06-22 | 09:30:00 | 2 |
| 2022-06-22 | 10:00:00 | 3 |
| 2022-06-22 | 10:30:00 | 4 |
| 2022-06-22 | 11:00:00 | 5 |
| 2022-06-23 | 09:00:00 | 1 |
| 2022-06-23 | 09:30:00 | 2 |
| 2022-06-23 | 10:00:00 | 3 |
Say now I want to loop though each row and modify the rn column, each rn is itself + rn from last row.
| _date | _time | rn |
|------------|----------|----|
| 2022-06-22 | 09:00:00 | 1 |
| 2022-06-22 | 09:30:00 | 3 |
| 2022-06-22 | 10:00:00 | 6 |
| 2022-06-22 | 10:30:00 | 10 |
| 2022-06-22 | 11:00:00 | 15 |
| 2022-06-23 | 09:00:00 | 16 |
| 2022-06-23 | 09:30:00 | 18 |
| 2022-06-23 | 10:00:00 | 21 |
How can I add row number and do that in same CTE scope?
I know I can probably get away with another CTE right after and use LAG() function to get previous row and do what ever modification I want with that rn column, but somehow I need to do this in one CTE and it is a little too complicated to explain.
Thank you in advance for any help!