如何解决Linq按条件求和
我有这个SQL查询,但不知道如何将其转换为VB.net LINQ
SELECT
clientid,SUM(IF(`type` = 1,cost,0)) AS advexp,SUM(IF(`type` = 3,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,0)),.genexp=g.Sum(Function(c) If(c.type=3,0))}
但无法编译。该查询旨在访问数据库。错误为Definition of method 'g' is not accessible in this context
。
解决方法
该问题并未说明是否使用了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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。