2

这是 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?

谢谢!

4

1 回答 1

2

这在 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)
        };
于 2012-10-29T22:52:24.443 回答