如何将此TSQL转换为Linq方法

时间:2018-08-31 10:17:12

标签: sql linq

我们有以下T-SQL查询:

SELECT TOP 10 
    AtheleteName, SUM(RankingScore) AS RankingScore
FROM
    [dbo].[TournamentBatchItem]
WHERE
    Gender = 'Male'
GROUP BY
    AtheleteName, Gender
ORDER BY 
    SUM(RankingScore) DESC

到目前为止,尝试以下动作,但尚未结束。订购不存在。有什么想法吗?

var top20ScoreMale = await _context.TournamentBatchItem
                                   .Where(t => t.Gender == "Male")
                                   .GroupBy( t => t.AtheleteName)
                                   .Select(t => new Stat2 { Name = t.Key, Value = t.Sum(i => i.RankingScore) })
                                   .Take(10)
                                   .ToListAsync();

1 个答案:

答案 0 :(得分:1)

在进入前10名之前,您需要对结果按其Value降序进行排序

var top10ScoreMale = await _context.TournamentBatchItem
                                .Where(t => t.Gender == "Male")
                                .GroupBy(t => t.AtheleteName)
                                .Select(g => new Stat2 { 
                                    Name = g.Key, 
                                    Value = g.Sum(x => x.RankingScore) 
                                })
                                .OrderByDescending(_ => _.Value)
                                .Take(10)
                                .ToListAsync();