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

如何使用LINQ语句从两张表查询数据?SQL转LINQ实现

问题:将原生SQL聚合查询改写为LINQ

我有一段通过原生SQL实现Cart表左联House表聚合查询的ASP.NET Core接口代码,希望将其改写为LINQ查询。以下是相关表结构、数据、我尝试的不完整LINQ代码以及预期查询结果,需要完成正确的LINQ查询实现。


原原生SQL实现的接口代码

[Route("Mode")]
[HttpGet]
public object Mode()
{
    string query = "Select Sum(c.total) as Total, Sum(h.Qty) as Qty, Sum(c.Amount) as Amount, Count(c.Item) as Count, " +
                   "c.Item, c.Model, h.Date From Cart c Left Join House as h On c.Id = h.Id Group By c.Item, c.Model, h.Date ";

    DataTable dt = new DataTable();
    string sqlDataSource = _configuration.GetConnectionString("DefaultConnection");

    SqlDataReader dr;

    using (SqlConnection con = new SqlConnection(sqlDataSource))
    {
        con.Open();

        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            dr = cmd.ExecuteReader();
            dt.Load(dr);
            dr.Close();
            con.Close();
        }
    }

    return new JsonResult(dt);
}

House表结构及数据

IdItemQty
1Apple15.00
2Orange17.00
3Carrot8.00

Cart表结构及数据

CIdItemQtyAmountTotalIdDate
1Apple22.004.00104/07/2024
2Apple22.004.00104/07/2024
3Orange53.0015.00205/07/2024
4Carrot42.008.00311/07/2024
5Carrot22.004.00311/07/2024

我尝试的不完整LINQ代码

IEnumerable DataSource = (from c in _context.Cart 
                          join h in _context.House on c.Id equals h.Id 
                          select t1).ToList();

预期输出结果

DateItemQtyAmountTotalCount
04/07/2024Apple22.008.002
05/07/2024Orange52.0015.001
11/07/2024Carrot62.0012.002

正确的LINQ实现

结合预期结果修正原SQL中的逻辑偏差(原SQL中Sum(h.Qty)与预期不符,实际应为聚合Cart表的Qty),同时实现左连接与分组聚合:

[Route("Mode")]
[HttpGet]
public IActionResult Mode()
{
    var result = from c in _context.Cart
                 // 左连接House表,确保Cart所有记录被保留
                 join h in _context.House on c.Id equals h.Id into houseGroup
                 from h in houseGroup.DefaultIfEmpty()
                 // 按Item和Date分组(原SQL的c.Model在Cart表中不存在,故忽略)
                 group c by new { c.Item, c.Date } into grouped
                 select new 
                 {
                     grouped.Key.Date,
                     grouped.Key.Item,
                     Qty = grouped.Sum(x => x.Qty),
                     Amount = grouped.Sum(x => x.Amount),
                     Total = grouped.Sum(x => x.Total),
                     Count = grouped.Count()
                 };

    return new JsonResult(result.ToList());
}

关键说明:

  1. 左连接实现:通过join ... into配合DefaultIfEmpty()实现SQL的Left Join逻辑,保证Cart表无匹配House记录的条目也能被查询到。
  2. 分组逻辑:根据预期结果调整分组字段为Item和Date,原SQL中的c.Model未在Cart表结构中出现,故移除该分组条件。
  3. 聚合计算:完全匹配预期结果的字段逻辑,分别计算Qty、Amount、Total的总和,以及分组内的记录数量。

内容的提问来源于stack exchange,提问作者Milie24

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:26:04