Man*_*wat 1 c# linq asp.net sql-server-2008 sql-to-linq-conversion
我有一个 SQL 查询,我想在 asp.net 应用程序中从 LINQ 调用它。
SELECT TOP 5 *
FROM (SELECT SongId,
DateInserted,
ROW_NUMBER()
OVER(
PARTITION BY SongId
ORDER BY DateInserted DESC) rn
FROM DownloadHistory) t
WHERE t.rn = 1
ORDER BY DateInserted DESC
Run Code Online (Sandbox Code Playgroud)
我不知道是否可以通过 linq 到 sql,如果不能,请提供任何其他方式。
我认为您必须将 SQL 分区更改为 Linq group-by。(实际上所有分区所做的都是按歌曲分组,并为每组选择最新的行。)所以是这样的:
IEnumerable<DownloadHistory> top5Results = DownloadHistory
// group by SongId
.GroupBy(row => row.SongId)
// for each group, select the newest row
.Select(grp =>
grp.OrderByDescending(historyItem => historyItem.DateInserted)
.FirstOrDefault()
)
// get the newest 5 from the results of the newest-1-per-song partition
.OrderByDescending(historyItem => historyItem.DateInserted)
.Take(5);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2618 次 |
| 最近记录: |