1

我正在努力尝试在正确的 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)

我这样做只是因为我想要一个好的表现,那就是表现不佳。所以我的问题是我怎样才能用聚合函数写一个正确的 LINQ 语句MAXCOUNT

更新:

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 的原因(当然,如果我删除了最大扩展名)。我想知道是否有办法在 T-SQL 查询中包含聚合函数 MAX 以提高服务器端的性能。

4

2 回答 2

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()
于 2013-01-20T06:58:45.460 回答
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();
于 2013-01-20T07:33:01.480 回答