我正在努力尝试在正确的T-SQL函数中生成此LINQ函数。
请检查以下句子:
// determine the max count of exams applied by students
IQueryable query = (from at in Database.Current.AnsweredTests
where at.TestId == id
group at by at.StudentId into s
select s.Count()).Max();
正如你所看到的,这个函数在语法上是错误的,因为Max
扩展返回int
。所以我想要完成的是生成一个正确的T-SQL。
这样的事情:
MAX(SELECT x.COUNT()
FROM...
GROUP BY StudentId)
我之所以这样做,是因为我想要一个好的表现,那就是表现不佳。所以我的问题是如何用MAX
和COUNT
等聚合函数编写正确的LINQ句子。
更新:
SELECT [GroupBy1].[A1] AS [C1]
FROM ( SELECT
[Extent1].[StudentId] AS [K1],
COUNT(1) AS [A1]
FROM [dbo].[AnsweredTests] AS [Extent1]
WHERE CAST( [Extent1].[TestId] AS int) = @p__linq__0
GROUP BY [Extent1].[StudentId]
) AS [GroupBy1]
这是生成IQueryable的原因(当然,如果我删除了max扩展名)。我想知道是否有办法在该T-SQL查询中包含聚合函数MAX,以提高服务器端的性能。
答案 0 :(得分:0)
您还可以通过以下方式提出查询:
SELECT TOP 1 COUNT(*)
FROM AnsweredTests
WHERE TestId = @id
GROUP BY StudentId
ORDER BY COUNT(*) DESC
遵循这个逻辑,这个(未经测试的)应该是你想要的:
var result = (from at in Database.Current.AnsweredTests
where at.TestId == id
group at by at.StudentId into s
orderby s.Count() descending
select s.Count()).First()
答案 1 :(得分:0)
你可以ORDER BY DESCENDING
然后先行:
var Max = (from at in Database.Current.AnsweredTests
where at.TestId == id
group at by at.StudentId into s
select new { Count = s.Count() }).OrderByDescending(o=>o.Count).First();