我有一个订单表,我希望按客户ID
获取最近的三个订单customer orderID orderDate
1 234 2018-01-01
1 236 2017-02-01
3 256 20157-03-01
我能够使用行号()来识别表中每行的行号,但有没有办法按客户ID获取最近的三个订单?有些客户的订单少于3个,而其他客户订单超过10个,因此我无法按行号指定。
是否有人有其他选项的建议?
答案 0 :(得分:3)
这是一个使用apply
的有趣方法(假设你有一个customers
表):
select o.*
from customers c cross apply
(select top 3 o.*
from orders o
where o.customerid = c.customerid
order by orderdate desc
) o;
答案 1 :(得分:2)
您可以使用partition by
;
select customerid, orderid,orderdate from (
select t.customerid, t.orderid,t.orderdate
,row_number() over (partition by t.customerid order by t.orderDate desc) as mostRecently
from samplecustomers t)
Records where mostRecently < 4
答案 2 :(得分:0)
试试这个:
SELECT *
FROM orders
WHERE customer = 1
ORDER BY orderDate ASC limit 3
这应该可以解决问题。
答案 3 :(得分:0)
使用此查询:
SELECT result.customer
, result.orderID
, result.orderDate
FROM
(
SELECT Temp.customer
, Temp.orderID
, Temp.orderDate
, ROW_NUMBER() OVER(PARTITION BY Temp.customer
ORDER BY Temp.orderDate DESC) AS MR
FROM YourTable AS Temp
) AS result
WHERE result.MR <= 3;