sql - 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
。
解决方案
该问题并未解释是否使用了 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
推荐阅读
- json.net - “从文档中提取的 PartitionKey 与标题中指定的不匹配” - 仅在 Azure 函数中
- excel - VBa复制错误“我们无法粘贴,因为复制和粘贴区域的大小不同”
- mysql - 在 MariaDB 中是否有等效的方法来执行 MySQL 的 JSONOBJECTAGG()?
- c# - c# 对象属性正在从缓存中加载
- excel - 找到特定单词后,删除该行和下面的 2 行。VBA可以做到这一点吗?
- domain-driven-design - 从有界上下文返回 HTML
- mysql - 无法通过 jdbc 连接我的数据库
- raspberry-pi3 - 如何在树莓派 3 上获取 UART 寄存器的值?
- ipfs - 如何完全卸载 IPFS 并从头开始重新启动所有内容并获得新的 peer id?
- python - Jupyter Notebook 上的大文件崩溃