You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带分组复杂求和的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:54:01