在 Master 中对记录进行分组,但希望对 Details 进行计数
Posted
技术标签:
【中文标题】在 Master 中对记录进行分组,但希望对 Details 进行计数【英文标题】:Group records in Master but want count for Details 【发布时间】:2021-09-09 11:25:21 【问题描述】:请考虑这些表格:
大师:
Id Year Season Flag City
------------------------------------------------------------------------------
1 2020 1 8000 Paris
2 2020 1 7000 Paris
3 2020 1 9000 London
4 2020 2 3000 Tokyo
5 2020 2 1000 Paris
6 2020 3 2000 Tokyo
7 2020 1 1000 London
8 2019 4 8000 Paris
9 2019 4 2000 Paris
详情:
Id MasterId Year Season CurrentFlag
--------------------------------------------------------------------------------------
1 8 2020 1 8000
2 9 2020 1 2500
3 8 2020 2 8100
4 1 2020 2 8000
5 2 2020 2 7500
6 2 2020 3 7500
7 3 2020 2 6000
8 4 2020 3 5000
9 7 2020 2 4000
将Master
视为我的记录生命周期的开始,将Details
视为在季节中显示CurrentFlag
。现在我想要一个Linq
查询,为(Year == 2010 and Season == 1)
带来这个结果:
City (Count Master All) (Count Master Flag<8000) (Count Details All) (Count Details Current Flag<8000)
---------------------------------------------------------------------------------------------------------
Paris 2 1 2 1
London 1 1 0 0
我写了这个查询:
var Records = (from m in master
join d in details
on m.Id equals d.MasterId into outerJoin
from d in outerJoin
where (m.Year == year && m.Dore == dore) ||
(d.Year == year && d.Dore == dore)
group m by new m.City into grp <--------
select new
City = grp.Key.City,
Count_Master_All = grp.Count(),
Count_Master_Below_8000 = grp.Where(o => o.Flag < 8000),
Count_Details_All = ???
Count_Details_Below_8000 = ???
).ToList();
第一个问题是我只能用m
对记录进行分组,所以我不能计算明细表的期望记录。我该怎么做?
谢谢
【问题讨论】:
【参考方案1】:稍后在查询中进行分组
var Records = (from m in master
join d in details
on m.Id equals d.MasterId into outerJoin
from d in outerJoin
where (m.Year == year && m.Dore == dore) ||
(d.Year == year && d.Dore == dore)
select new m = m, d = d)
.GroupBy(x => new x.m.City )
.Select(grp => new
City = grp.Key.City,
Count_Master_All = grp.Count(),
Count_Master_Below_8000 = grp.Where(o => o.Flag < 8000),
Count_Details_All = grp.Count()
).ToList();
【讨论】:
谢谢,但是Count_Details_Below_8000
呢?
会是这样的:Count_Details_All = grp.Where(d => d.CurrentFlag
以上是关于在 Master 中对记录进行分组,但希望对 Details 进行计数的主要内容,如果未能解决你的问题,请参考以下文章
在 XSLT 中对记录进行分组时如何避免 O(n^2) 复杂性?