Linq2SQL帮助转换row_number和分区

时间:2013-09-12 09:04:49

标签: c# tsql linq-to-sql

有人可以帮我转换下面的t-sql到c#linq?

select
    clientid,
    orderId 
from 
(
    select
        row_number() over (partition by clientid order by purchasedate desc) as rownum,
        clientid,
        id as orderId   
    from ordertraining
) as x where rownum = 1

1 个答案:

答案 0 :(得分:1)

您可以使用以下LINQ查询获得相同的结果:

from o in Orders
group o by o.clientId into g
select g.OrderByDescending(x => x.purchasedate).FirstOrDefault();

但它不会生成相同的SQL。它将使用CROSS APPLY代替。