【发布时间】: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 我删除了示例查询,但它们工作正常。