我试图使用LINQ SQL来查询我的数据库。
让我们说我有一些看起来像这样的数据:
var1 var2 var3 qty
1 a 1a 50
1 a 1a 25
2 b 2b 10
2 b 2b 15
2 b 2b 10
3 a 3a 25
我知道如何在SQL中格式化我的查询。它会是这样的:
SELECT var1, var2, var3, count(*) AS count, sum(qty) As quantity
FROM MyTable
GROUP BY var1, var2, var3
在这种情况下,输出将是这样的:
var1 var2 var3 Count Qty
1 a 1a 2 75
2 b 2b 3 35
3 a 3a 1 25
如何在vb.net中使用LINQ做同样的事情
Dim groups = From j In MyTable
Group By j.var1, j.var2, j.var3 Into g
Select new {var1 = g.var1,
var2 = g.var2,
var3 = g.var3,
quantity = sum(g.qty),
count = count(*)}
这不太对,但我认为它很接近。我不会在VB.NET中理解该组的语法。
答案 0 :(得分:2)
您必须使用anonymous type,如下所示: -
Group j By Key = New With { Key .Var1 = j.var1,
Key .Var2 = j.var2,
Key .Var3 = j.var3 } Into Group
Select New With { .var1 = Key.Var1,
.var2 = Key.Var2,
.var3 = Key.Var3,
.quantity = Group.Sum(Function(x) x.qty),
.count = Group.Count()
}
答案 1 :(得分:2)
您希望按匿名类型进行分组,这是VB.NET中的语法(请注意Key
):
Dim groups =
From j In MyTable
Group By x = New With {Key .var1 = j.var1, Key .var2 = j.var2, Key .var3 = j.var3} Into g = Group
Select New With {
.var1 = x.var1,
.var2 = x.var2,
.var3 = x.var3,
.quantity = g.Sum(Function(r) r.qty),
.count = g.Count()
}