LINQ to SQL查询将两列相乘并计算SUM

时间:2012-10-29 20:29:11

标签: c# .net linq linq-to-sql

这是SQL查询

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?

谢谢!

1 个答案:

答案 0 :(得分:0)

这在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)
        };