Skip to content
Advertisement

SQL – Pick first row satisfying a condition below every row satisfying another condition

Suppose I have this table, named Table

I want this result:

That is:

  • If Col1 = A and Col2 = 1, take the corresponding row
  • If Col1 = A and Col2 = 0, take the first row below it where Col2 = 1

I tried something like

but it’s not quite what I was looking for. I couldn’t come up with any solution. What should I do?

Advertisement

Answer

Use window functions SUM() and MIN():

See the demo.
Results:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement