Linq相当于一个表中的sql语句,但包含基于该表中的组的计数
对不起,这个标题太糟糕了,我不知道该用什么术语 我有一个简单的表格(称为“材料”): 一些样本数据:Linq相当于一个表中的sql语句,但包含基于该表中的组的计数,sql,vb.net,linq,Sql,Vb.net,Linq,对不起,这个标题太糟糕了,我不知道该用什么术语 我有一个简单的表格(称为“材料”): 一些样本数据: ID Desc Maintype SubType 1 Aluminium 3003 Metal Aluminium 2 Bamboo Wood Softwood 3 Cellulose Acetate Polymer
ID Desc Maintype SubType
1 Aluminium 3003 Metal Aluminium
2 Bamboo Wood Softwood
3 Cellulose Acetate Polymer CA
4 Cork Wood Composite
5 Stainless Steel Metal Steel
6 Tinplate Metal Steel
7 PA (Type 11, Unfilled) Polymer PA
8 PA (Type 12, Unfilled) Polymer PA
9 PA (Type 46, Extrusion) Polymer PA
10 Palm Wood Softwood
我只需要一个有序(按maintype、子类型)的材质列表(未分组),包括数据集中每个材质maintype和子类型的出现次数,如下所示:
ID Desc Maintype SubType CountMain CountSub
1 Aluminium 3003 Metal Aluminium 3 1
5 Stainless Steel Metal Steel 3 2
6 Tinplate Metal Steel 3 2
3 Cellulose Acetate Polymer CA 4 1
7 PA (Type 11, Unfilled) Polymer PA 4 3
8 PA (Type 12, Unfilled) Polymer PA 4 3
9 PA (Type 46, Extrusion) Polymer PA 4 3
4 Cork Wood Composite 3 1
2 Bamboo Wood Softwood 3 2
10 Palm Wood Softwood 3 2
在SQL中,这是一个棘手的问题:
SELECT Id
,MaterialName
,MaterialType
,MaterialSubType
,(select count(id) from materials m2 where m2.materialType=m1.materialType) as CountMain
,(select count(id) from materials m2 where m2.materialSubType=m1.materialSubType) as CountSub
FROM materials m1
order by materialType, MaterialSubType
然而在林克,我无法接近它。这可能是因为我使用vb,在group和into方面存在一些语法上的困难。我甚至不能得到linq表达式的一个干净的编译,因为我不能解决由“group”和“into”以及“count”引起的可怕的上下文问题。由于我不知道用于“计数”结果的子查询的正确技术术语,因此我找不到任何这样做的示例。也许是因为我做错了
我相信对于理解linq查询的人来说,这将是非常简单的-如果有在线教程或其他东西可以告诉我如何实现这一点,我希望您能给我一个指针或简短的解释,说明如何在linq中实现这一点。Sods法则,我在发布之后就解决了
from mat in materials
order by mat.mainType, mat.subType
select new with {
mat.Id,
mat.MaterialName,
mat.MainType,
mat.SubType,
.countMain = (Aggregate m2 in materials
where m2.MainType=mat.MainType
into Count()),
.countSub = (Aggregate m2 in materials
where m2.SubType=mat.SubType
into Count())
}
from mat in materials
order by mat.mainType, mat.subType
select new with {
mat.Id,
mat.MaterialName,
mat.MainType,
mat.SubType,
.countMain = (Aggregate m2 in materials
where m2.MainType=mat.MainType
into Count()),
.countSub = (Aggregate m2 in materials
where m2.SubType=mat.SubType
into Count())
}