至少对于 LINQ to SQL,count 函数的缺点是每个 .count 方法需要单独的 SQL 请求。我怀疑 Jessie 试图对表进行一次扫描,而不是对每个谓词进行多次扫描。根据您创建的逻辑和列数,这可能效果不佳。更接近原始请求,尝试将 sum 与三元 if 子句一起使用(来自 Northwind):
from e in Employees
group e by "" into g
select new {
isUs = g.Sum (x => x.Country == "USA" ? 1 : 0),
NotUs = g.Sum (x => x.Country != "USA" ? 0 : 1)
}
LINQ to SQL 生成以下内容(带有其他 ORM 的 YMMV):
SELECT SUM(
(CASE
WHEN [t1].[Country] = @p1 THEN @p2
ELSE @p3
END)) AS [isUs], SUM(
(CASE
WHEN [t1].[Country] <> @p4 THEN @p5
ELSE @p6
END)) AS [NotUs]
FROM (
SELECT @p0 AS [value], [t0].[Country]
FROM [Employees] AS [t0]
) AS [t1]
GROUP BY [t1].[value]