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

标签 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?

谢谢!

最佳答案

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

关于c# - LINQ to SQL查询将两列相乘并计算SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13129135/

相关文章:

c# - 如何在加载数据后显示我的 Silverlight 应用程序?

c# - 在 MVC Controller 中将 Javascript 时间字符串转换为 DateTime 或 TimeSpan

c# - 如何获取对象具有的属性数?

.net - 在抛出 OutOfMemoryException 之前调用 GC.Collect

c# - 如何通过提供ID列表从列表中查询对象

c# - 计算条目数?

c# - 可以重复 XAML block ,foreach 样式吗?

c# - Unity3d - 在 RTS 相机上拖放对象

.net - 如何在 Visual Studio 中调试 Windows PowerShell 模块?

c# - 寻找最小值时避免魔数(Magic Number)