Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Hammerklavier
Starting Member
26 Posts |
Posted - 2015-01-06 : 15:01:01
|
Hi,Suppose I have a table called Order that stores an OrderID, CustomerID, OrderType and OrderDate. How could I write a query to return a list of customers whose five most recent orders (based on the OrderDate) feature the same OrderType?If only four of the five most recent for a given customer feature the OrderType, then none of them would be returned.I greatly appreciate any assistance! |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2015-01-06 : 16:17:24
|
[code]select * from orderwhere OrderDate in ( select top(5) OrderDate from Order order by OrderDate desc where OrderDate is not null)[/code] |
|
|
ehorn
Master Smack Fu Yak Hacker
1632 Posts |
Posted - 2015-01-06 : 16:26:59
|
[code]select d.customerid, d.orderID, d.ordertypefrom ( select *, row_number() over (partition by customerID, orderID, orderType order by orderDate desc) as ct from @order) dwhere d.ct = 5group by d.customerid, d.orderID, d.ordertype[/code] |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2015-01-07 : 07:53:02
|
[code]-- SwePesoSELECT c.CustomerID, MIN(f.OrderType) AS OrderTypeFROM ( SELECT CustomerID FROM dbo.[Order] GROUP BY CustomerID HAVING COUNT(*) >= 5 ) AS cCROSS APPLY ( SELECT TOP(5) o.OrderType FROM dbo.[Order] AS o WHERE o.CustomerID = c.CustomerID ORDER BY o.OrderDate DESC ) AS fGROUP BY c.CustomerIDHAVING MIN(f.OrderType) = MAX(f.OrderType);[/code] Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA |
|
|
Hammerklavier
Starting Member
26 Posts |
Posted - 2015-01-07 : 12:52:59
|
Thank you for the responses.SwePeso, your query did the trick! |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
|
|
|
|