如何将带分组复杂求和的SQL查询转换为Linq语句
Linq实现方案
以下分两种常用场景给出对应写法:
1. Entity Framework/EF Core 场景(可自动转换为等效SQL在数据库执行)
// 提前获取当前月份,对应SQL中的 MONTH(getdate()) var currentMonth = DateTime.Now.Month; var query = dbContext.Service .GroupBy(s => new { s.id, s.serverPlace }) .Select(g => new { id = g.Key.id, serverPlace = g.Key.serverPlace, sum = g.Sum(s => s.count * 12 + currentMonth) });
说明:你需要的sum求和逻辑直接写在
Sum()方法的入参表达式中即可,和SQL中sum内的计算规则完全对应。提前提取currentMonth的写法会被EF识别为常量,和原SQL的执行逻辑完全一致,不会出现逐行计算当前时间的问题。如果需要直接在Linq中调用SQL日期函数避免提前计算月份,EF Core 3.0+版本可以用EF.Functions.DatePartMonth(DateTime.Now)替换currentMonth,执行效果完全相同。
2. 内存集合场景(Linq to Objects)
如果你的Service数据已经全部加载到内存中,直接用以下写法即可:
var currentMonth = DateTime.Now.Month; var result = serviceList .GroupBy(s => new { s.id, s.serverPlace }) .Select(g => new { g.Key.id, g.Key.serverPlace, sum = g.Sum(s => s.count * 12 + currentMonth) }) .ToList();
内容的提问来源于stack exchange,提问作者Inside Man
相关产品推荐
相关产品推荐

