SQL每个客户端的最后订单

时间:2018-06-14 10:23:19

标签: sql greatest-n-per-group

我有一个表dbo.tbl_orders,我收集数据为:

Date
clientName
Amount

如何创建一个视图,我可以在每个客户端看到它们的最后一个订单的日期?

谢谢!

3 个答案:

答案 0 :(得分:1)

CREATE VIEW last_client_order_date as
SELECT ClientName, max(Date) 
FROM tbl_orders
GROUP BY ClientName

答案 1 :(得分:0)

获取每个客户的最新订单日期

select [ClientId], max([Date]) from [Orders] group by [ClientId]

获取每个客户的最新订单

只需将上面的查询与订单表

连接起来
select * from [Orders] 
join ( select [Clientid], max([Date]) from [Orders] group by [ClientId] ) as [LatestOrders] 
on [LatestOrders].Date = [Orders].Date 
and [LatestOrders].[ClientId] = [Orders].[ClientId]
  

注意:如果两个订单的日期相同,您可能会为每个客户收到多个订单

答案 2 :(得分:0)

没有测试过这个,但这是你需要的吗?

Select * 
FROM dbo.tbl_orders 
WHERE clientName = value 
AND Date = (select max(Date) 
   from dbo.tbl_orders 
   where clientName = value)

value是您正在寻找的clientName