【问题标题】:Linq Group By Sum based on a conditionLinq Group By Sum 基于条件
【发布时间】:2021-01-24 20:06:30
【问题描述】:

我有这个 SQL 查询,但不知道如何将其转换为 VB.net LINQ

SELECT 
    clientid, 
    SUM(IF(`type` = 1, cost, 0)) AS advexp,  
    SUM(IF(`type` = 3, cost, 0)) AS genexp 
FROM customerlist 
WHERE clGroupId=pGroupId 
GROUP BY clientid;

customerlist 包括一个字段type 和一个字段cost。目的是在一个查询中获得类型 1 和类型 3 的费用。

这是我尝试过的:

From p In db.customerlist
Where p.clGroupId=1 
Group By p.clientid,p.type Into g 
Select New With { .clientid=g.clientd,.advexp=g.Sum(Function(c) If(c.type=1, cost,0)),.genexp=g.Sum(Function(c) If(c.type=3, cost,0))}

但无法编译。该查询旨在命中数据库。错误是Definition of method 'g' is not accessible in this context

【问题讨论】:

  • 这两个 LINQ 查询无效。您是在使用 ORM 还是尝试在内存中对 List 进行分组?在内存中复制原始查询很容易,几乎与 SQL 查询相同
  • 按多列分组:customerList.Where(c => c.GroupId == groupId).GroupBy(c => new { c.ClientId, c.Type }).Select(g => new { Group = g.Key, Total = g.Count * cost })
  • 这两个查询工作正常。我跳过了db.customerlist.tolist
  • @AllenKing 这两个 LINQ 查询无效。你不能写into genexp=sum(cost),
  • @PanagiotisKanavos 我删除了示例查询,但它们工作正常。

标签: sql vb.net linq


【解决方案1】:

这个问题没有解释是否使用了 ORM 或 customerlist 是什么。内存中的客户列表,还是 DbSet?

如果这是一个列表,则 LINQ 查询将与 SQL 查询几乎相同:

from customer in customerlist
where p.clGroupId=pGroupId 
group by p.clientid into g
select new { clientid=g.Key,
             advexp=g.Sum(c=>c.type==1?cost:0),
             genexp=g.Sum(c=>c.type==3?cost:0)
}

根据使用的 ORM 和数据库提供程序,EF 或 NHibernate 可能能够将相同的查询转换为 SQL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2021-06-13
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多