-1

This is hard to explain so I will give an example. I need SQL (ms server), I assume its with row_number over partition but can't get it to work.

I have this table:

ID PreviousID Data
1 a
2 1 b
3 2 c
4 d
5 4 e
6 f

I want these results:

ID NewID Data
1 1 a
2 1 b
3 1 c
4 2 d
5 2 e
6 3 f

And another with just the new IDs of each sequence:

NewID Data
1 a
2 d
3 f

Instead of a row number new id, it could also have the first id of the sequence, whatever is easier, as long as it identifies the sequence.

CoolkcaH
  • 195
  • 1
  • 6
  • As per the question guide, please show what you’ve tried and tell us what you found (on this site or elsewhere) and why it didn’t meet your needs. – Dale K May 19 '22 at 10:48

1 Answers1

2

Seems you want a windowed COUNT of rows where the value of PreviousID is NULL.

SELECT ID,
       COUNT(CASE WHEN PreviousID IS NULL THEN 1 END) OVER (ORDER BY ID) AS NewID,
       Data
FROM dbo.YourTable;
Larnu
  • 76,706
  • 10
  • 34
  • 63
  • This works, thanks. How do I get the last table, basically the first of each newid? – CoolkcaH May 19 '22 at 10:52
  • [Get top 1 row of each group](https://stackoverflow.com/questions/6841605/get-top-1-row-of-each-group) @CoolkcaH . – Larnu May 19 '22 at 10:57
  • When I try a row_number over that I get an error "Windowed functions cannot be used in the context of another windowed function or aggregate." – CoolkcaH May 19 '22 at 10:58
  • You'll need to use 2 CTEs, @CoolkcaH . – Larnu May 19 '22 at 10:59