在 select 中對群組 g 呼叫彙總方法,只回傳統計結果而非完整明細,SQL 轉譯為單一 GROUP BY 查詢,效能極佳。
var q = from p in db.Products
group p by p.CategoryID into g
select new { g.Key, NumProducts = g.Count() };
var q = from p in db.Products
group p by p.CategoryID into g
select new { g.Key, NumProducts = g.Count(p => p.Discontinued) };
Count(predicate) 中的 p 代表群組內的單一產品元素。
// 最高價
select new { g.Key, MaxPrice = g.Max(p => p.UnitPrice) }
// 最低價
select new { g.Key, MinPrice = g.Min(p => p.UnitPrice) }
// 平均價
select new { g.Key, AveragePrice = g.Average(p => p.UnitPrice) }
// 價格總和
select new { g.Key, TotalPrice = g.Sum(p => p.UnitPrice) }
執行時 LINQ to SQL 僅發送彙總 SQL,不載入明細資料(參考上篇 SQL 觀察)。
var q = from p in db.Products
group p by p.CategoryID into g
where g.Count() >= 10
select new { g.Key, ProductCount = g.Count() };
轉譯 SQL 會在外層包裝子查詢:
SELECT [t1].[CategoryID], [t1].[value2] AS [ProductCount]
FROM (
SELECT COUNT(*) AS [value], COUNT(*) AS [value2], [t0].[CategoryID]
FROM [dbo].[Products] AS [t0]
GROUP BY [t0].[CategoryID]
) AS [t1]
WHERE [t1].[value] >= @p0 -- @p0 = 10