Query the latest two orders of a customer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.