(from pd in context.Report
where pd.ReportDate.Month == 2012
&& pd.ReportDate.Year == 11 && pd.UserID == 11014
group pd by pd.UserID into g
select new
{
Cost = g.Sum(pd => pd.Cost),
RevenueUSD = g.Sum(pd => pd.Revenue),
});
此查询
-- Region Parameters
DECLARE @p0 Int = 2012
DECLARE @p1 Int = 11
DECLARE @p2 Int = 11014
-- EndRegion
SELECT SUM([t0].[Cost]) AS [Cost], SUM([t0].[Revenue]) AS [RevenueUSD]
FROM [IntegratedPublisherData] AS [t0]
WHERE (DATEPART(Month, [t0].[ReportDate]) = @p0) AND (DATEPART(Year, [t0].[ReportDate]) = @p1) AND ([t0].[UserID] = @p2)
GROUP BY [t0].[UserID]
但我想要
-- Region Parameters
DECLARE @p0 Int = 2012
DECLARE @p1 Int = 11
DECLARE @p2 Int = 11014
-- EndRegion
SELECT SUM([t0].[Cost]) AS [Cost], SUM([t0].[Revenue]) AS [RevenueUSD]
FROM [IntegratedPublisherData] AS [t0]
WHERE (DATEPART(Month, [t0].[ReportDate]) = @p0) AND (DATEPART(Year, [t0].[ReportDate]) = @p1) AND ([t0].[UserID] = @p2)
此查询将返回1行,因为UserID被选择为一个值,并且按UserID分组。
如何在没有分组的情况下使用Sum编写此Linq查询?
答案 0 :(得分:1)
如果查询返回多行,这也将解决您的问题。也适用于单行。
var query =
(from pd in context.Report
where pd.ReportDate.Month == 11
&& pd.ReportDate.Year == 2012
&& pd.UserID == 11014
select pd).ToList() //use .ToList() to avoid doubled execution
var result =
new
{
Cost = query.Sum(pd => pd.Cost),
RevenueUSD = query.Sum(pd => pd.Revenue)
};
答案 1 :(得分:0)
删除分组,并从表中读取值。当只有一条记录时,您不需要sum
:
from pd in context.Report
where pd.ReportDate.Month == 2012 && pd.ReportDate.Year == 11 && pd.UserID == 11014
select new {
Cost = pd.Cost,
RevenueUSD = pd.Revenue,
}