serengeti12
serengeti12

Reputation: 5586

getting next row in sql with a loop

I might not have the best title for my question but this is what I mean. I have this result which results after a query with a couple of joins.

 id  | owner_id     |   name    |        order | count 
-----+--------------+-----------+--------------+-------
 274 |        25041 | first     |            1 |     0
 269 |        25041 | second    |            2 |     2
 275 |        25041 | third     |            3 |     0
 276 |        25041 | fourth    |            4 |     0
 273 |        25041 | fifth     |            5 |     1
 277 |        25041 | sixth     |            6 |     0

and I need a query that use is to add a column with the next name depending using the order column above. It should loop that it should say after the sixth follows the first.

 id  | owner_id     |   name    |        order | count |   next    
-----+--------------+-----------+--------------+-------+-----------
 274 |        25041 | first     |            1 |     0 | second
 269 |        25041 | second    |            2 |     2 | third
 275 |        25041 | third     |            3 |     0 | fourth
 276 |        25041 | fourth    |            4 |     0 | fifth
 273 |        25041 | fifth     |            5 |     1 | sixth
 277 |        25041 | sixth     |            6 |     0 | first

Upvotes: 0

Views: 851

Answers (1)

bvr
bvr

Reputation: 4826

Try this

select t1.*
,CASE WHEN t2.name IS NULL THEN 'first' ELSE t2.name END as next 
from  Table1 as t1
LEFT join Table1 as t2 on t1.order = t2.order-1

SQL FIDDLE DEMO

Upvotes: 1

Related Questions