使用较低级别组中的顶级组的聚合结果 [英] Using result of aggregate from top level group inside lower level group
问题描述
我有2个表A {int id,int grp},B {int aid,int cat}。
表B包含表的记录A属于,所以B.aid是引用A.id的Foreign Key。
A.id是表A的唯一主键。
B.cat包含从1到5的类别编号,A.grp包含从1到1000的数字。
表A有300万记录,表B - 约5百万。
对于每个组A.grp,我需要计算A中包含B.cat的记录的%如果A:[{1,1},{2,1},{3,2}],B:[{1, 3},{1,4},{2,3},{3,4}],那么查询的结果应该是以下3列表:
R {int grp,int cat,double%}: [{1,3,100},{1,4,50},{2,4,100}]
如何使用Linq中的单一查询? p>
希望A在查询中只出现一次,因为我想要将A替换为A.Where(e =>一些复杂的表达式),而不重复它
表A和B被导入具有外键的Linq to Entities,以便可以从A中引用从b中选择b在b中选择b.cat
或从b中选择 select bAgrp
您可以组合这样的查询
var query = from g in
(来自于db.A
组a由新的
{
grp = a.grp
}
)
在$ b中加入c $ b(来自a中的db.A
来自b的aB
组b通过新的
{
a.grp,
b.cat
}
)g.Key.grp上的
等于c.Key.grp
select new
{
g.Key.grp,
c.Key。 cat,
percent = c.Count()* 100 / g.Count()
};
I have 2 tables A{int id,int grp}, B{int aid,int cat}.
Table B contains list of categories that record of table A belongs to, so B.aid is Foreign Key that references A.id.
A.id is unique primary key of table A.
B.cat contains category number from 1 to 5, A.grp contains numbers from 1 to 1000.
Table A has 3 million of records, table B - about 5 million.
For each group A.grp I need to calculate % of records in A that contain B.cat out of number of records within group A.grp.
So if A:[{1,1},{2,1},{3,2}], B:[{1,3},{1,4},{2,3},{3,4}] then result of the query should be the following 3 column table: R{int grp,int cat,double percent}:[{1,3,100},{1,4,50},{2,4,100}]
How can I do it with one single query in Linq ?
It is desired that A to appear only once in that query because I want to be able to replace A with A.Where(e=>some complicated expression) without duplicating it many times in that single query.
Tables A and B are imported into Linq to Entities with foreign keys so that it's possible to reference from a in A from b in a.B select b.cat
or from b in B select b.A.grp
You can combine your queries like this
var query = from g in
(from a in db.A
group a by new
{
grp = a.grp
}
)
join c in
(from a in db.A
from b in a.B
group b by new
{
a.grp,
b.cat
}
)
on g.Key.grp equals c.Key.grp
select new
{
g.Key.grp,
c.Key.cat,
percent = c.Count() * 100 / g.Count()
};
这篇关于使用较低级别组中的顶级组的聚合结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!