Declare @ I int
Set @ I = 0
Declare @ temp table
(
Id int,
Customerid nvarchar (500 ),
City nvarchar (500 ),
Orderid int
)
Insert @ temp
Select Top 100 percent row_number () over (order by C. customerid, O. orderid DESC) as ID, C. customerid, city, O. orderid from customers as C inner join
Orders as O
On C. customerid = O. customerid
Order by ID
Declare @ temp1 table
(
Id int,
Customerid nvarchar (500)
)
Insert @ temp1
Select min (ID), customerid from @ temp group by customerid
Declare @ temp2 table
(
Id int,
Customerid nvarchar (500)
)
Insert @ temp2
Select * From @ temp1
Union
Select T1. * from (
Select ID + 1 as ID, customerid from @ temp1) T1
Inner join @ temp t on t1.customerid = T. customerid
And t1.id = T. ID
Select temp. customerid, city, temp. orderid from @ temp as temp inner join
@ Temp2 as temp2
On temp. ID = temp2.id
Order by temp. customerid, orderid DESC
Simple Method:
Select C. customerid, city, Ca. orderid from customers as C
Cross apply
(Select Top 2 orderid, customerid from orders as O
Where C. customerid = O. customerid order by orderid DESC) as CA