【发布时间】:2014-07-01 14:19:14
【问题描述】:
我想根据一个总和和一个计数来做一个分组。我似乎无法在 linq 中创建解决方案。如何将我的查询转换为 linq?
SELECT HistoricalBillingProductGroup,
COUNT(*),
BillingPeriod,
SUM(TotalMonthlyChargesOtcAndMrc)
FROM [x].[dbo].[tblReport]
group by BillingPeriod, HistoricalBillingProductGroup
order by BillingPeriod
这是我迄今为止在 Linq 中得到的结果
var result =
context.Reports.GroupBy(x => new {x.BillingPeriod, x.HistoricalBillingProductGroup})
.Select(x => new StatisticsReportLine
{
HistoricalBillingGroup = x.FirstOrDefault().HistoricalBillingProductGroup,
BillingPeriod = x.FirstOrDefault().BillingPeriod,
CountOfRows = x.Count(),
SumOfAmount = x.Sum(p => p.TotalMonthlyChargesOtcAndMrc) ?? 0
})
.ToString();
我从中得到的查询非常庞大,需要很长时间才能加载。在 SQL 中,它只需几毫秒。我几乎不怀疑这是解决方案。
【问题讨论】:
-
context.Reports的类型是什么?你看过生成的 SQL 了吗? -
我从我的代码优先域上下文中获取报告,生成的 SQL 就像答案所说的带有一些子查询。我猜这就是它变慢的原因。
标签: c# sql sql-server linq