SQL 服务器 - 查询 - 如何获取子查询的最后结果?
SQL Server - Query - How to get the last result of a subquery?
我要数据表。第一个有用户:
第二个是他们的订单。
是否可以获取完整的用户列表及其各自的最后订单?像这样:
这是我的尝试,但不允许:
select a.id ,a.Name , b.Order ,b.Date
from users as a
left join (
select top 1 Orders.id , Orders.order , Orders.Date
from Orders
where Orders.id = a.id
order by orders.Date desc
) as b
on a.ID = b.Id
一种方法是使用 window 函数:
select *
from Users u
left join (
select * , row_number() over (partition by ID order by date desc) rn
from orders
) t on t.rn = 1 and u.id = t.id
我要数据表。第一个有用户:
第二个是他们的订单。
是否可以获取完整的用户列表及其各自的最后订单?像这样:
这是我的尝试,但不允许:
select a.id ,a.Name , b.Order ,b.Date
from users as a
left join (
select top 1 Orders.id , Orders.order , Orders.Date
from Orders
where Orders.id = a.id
order by orders.Date desc
) as b
on a.ID = b.Id
一种方法是使用 window 函数:
select *
from Users u
left join (
select * , row_number() over (partition by ID order by date desc) rn
from orders
) t on t.rn = 1 and u.id = t.id