這裏的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