首页 > 解决方案 > Linq Group By Sum 基于条件

问题描述

我有这个 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

标签: sqlvb.netlinq

解决方案


该问题并未解释是否使用了 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


推荐阅读