这里的SQL查询LINQ to SQL查询乘两列和计算SUM
Select sum(f.Acres*m.credit1), sum(f.Acres*m.credit2), sum(f.Acres*m.credit3)
from first f join model m on f.Id = m.fID
where m.year == 2012
如何写LINQ这上面的SQL?
谢谢!
这里的SQL查询LINQ to SQL查询乘两列和计算SUM
Select sum(f.Acres*m.credit1), sum(f.Acres*m.credit2), sum(f.Acres*m.credit3)
from first f join model m on f.Id = m.fID
where m.year == 2012
如何写LINQ这上面的SQL?
谢谢!
这在Linq中有点棘手,因为您需要一个组来完成聚合。通过对虚值,分组喜欢它下面会工作:
var q = from f in first
join m in model on f.Id equals m.fID
where m.year == 2012
group new { f, m } by 1 into g
select new
{
credit1 = g.Sum(x => x.f.Acres * x.m.credit1),
credit2 = g.Sum(x => x.f.Acres * x.m.credit2),
credit3 = g.Sum(x => x.f.Acres * x.m.credit3)
};
编辑
从阅读您的意见。 如果你想让它每年组,你这是怎么做到这一点:
var q = from f in first
join m in model on f.Id equals m.fID
where m.year >= 2014 && m.year <= 2020
group new { f, m } by m.year into g
select new
{
year = g.Key,
credit1 = g.Sum(x => x.f.Acres * x.m.credit1),
credit2 = g.Sum(x => x.f.Acres * x.m.credit2),
credit3 = g.Sum(x => x.f.Acres * x.m.credit3)
};
第四砸在谷歌.. http://download.damieng.com/dotnet/LINQToSQLCheatSheet.pdf(PDF方式) –
感谢您的评论。然而,我在乘法和计算总和方面遇到困难。乘法必须从连接中的两个不同的表中完成,我不知道该怎么做。 – Aqua267