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

如何将含Join、Group By和Count的SQL查询转换为LINQ?

SQL转LINQ实现

原SQL逻辑

关联Descarga_XML_recepcion_V2与EnterpriseSGE表,按idempresa和企业名称分组,统计每组记录数量,返回企业名称、企业ID、统计数三个字段。

原SQL代码:

select b.Name,a.idempresa,count(1) as cuenta 
from Descarga_XML_recepcion_V2 as a
inner join EnterpriseSGE as b on a.idempresa = b.EnterpriseSGEId 
group by idempresa,b.name

LINQ实现(两种写法)

查询语法

var result = from a in db.Descarga_XML_recepcion_V2
             join b in db.EnterpriseSGE on a.idempresa equals b.EnterpriseSGEId
             group new { a, b } by new { a.idempresa, b.Name } into grouped
             select new 
             {
                 Name = grouped.Key.Name,
                 IdEmpresa = grouped.Key.idempresa,
                 Cuenta = grouped.Count()
             };

方法语法

var result = db.Descarga_XML_recepcion_V2
    .Join(db.EnterpriseSGE,
          a => a.idempresa,
          b => b.EnterpriseSGEId,
          (a, b) => new { a, b })
    .GroupBy(item => new { item.a.idempresa, item.b.Name })
    .Select(grouped => new 
    {
        Name = grouped.Key.Name,
        IdEmpresa = grouped.Key.idempresa,
        Cuenta = grouped.Count()
    });

返回结果示例

name1 | 5041 | 583
name2 | 4031 | 1730
name3 | 5042 | 640
name4 | 4034 | 300
name5 | 6047 | 861
name6 | 5043 | 187
name7 | 4033 | 318

内容的提问来源于stack exchange,提问作者Roberto González Moreno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:00:58