gpt4 book ai didi

c# - Linq to sql计算查询中一组项目的百分比

转载 作者:太空宇宙 更新时间:2023-11-03 15:34:34 25 4
gpt4 key购买 nike

Linq to SQL 新手和 SQL 新手。第一次发帖,请多多关照。
我有类似于下表的内容,我正在基于 C# 中的日期范围查询 dataGridView。

HeatNumber ChargeNumber 重量 DOB

1            1              500     8/26/15
1 2 3500 8/26/15
1 3 2200 8/26/15
2 1 2000 8/27/15
2 2 1100 8/27/15

var query = from SU in dct.GetTable<ScrapInCharge>()
where ((SU.DOB >= dateTimePicker2.Value.Date) &&
(SU.DOB <= dateTimePicker1.Value.Date))
orderby SU.HeatNumber descending
select SU;
scrapInChargeBindingSource.DataSource = query;

我需要添加一个列来显示每个 ChargeNumber 占总 HeatNumber 权重的百分比。我确实想出了如何通过 HeatNumber 获得每个热量的总重量。

var TotalHeatWgt = from a in dct.ScrapInCharges
where ((a.DOB >= dateTimePicker2.Value.Date) &&
(a.DOB <= dateTimePicker1.Value.Date))
group a.Weight by a.HeatNumber
into b
select new { HeatNumber = b.Key, TotalWgt = b.Sum() };

我目前正在研究如何将其合并到一个 C# 查询中,在权重列之后插入一个 % of Heat 列。可以这样做吗,或者我是否需要将未绑定(bind)的列添加到 dataGridView % of Heat 并使用我的 TotalHeatWgt 查询的返回值遍历行?

最佳答案

简单尝试:

var results = data.Select(d => new {
d.HeatNumber,
d.ChargeNumber,
d.Weight,
Percent = 100.0 * d.Weight / data.Where(dd => dd.HeatNumber == d.HeatNumber).Sum(dd => dd.Weight)
});

from row in data
select new {
row.HeatNumber,
row.ChargeNumber,
row.Weight,
Percent = 100.0 * row.Weight / (from innerRow in data
where innerRow.HeatNumber == row.HeatNumber
select innerRow.Weight
).Sum()
};

下面的会更高效(至少在内存中,我不确定它在 SQL 中是否会更好):

var results = data.GroupBy (d => d.HeatNumber)
.SelectMany (grp => grp.Select(row => new {
row.HeatNumber,
row.ChargeNumber,
row.Weight,
Percent = 100.0 * row.Weight / grp.Sum(dd => dd.Weight)
})
);

以及查询语法:

from row in data 
group row by row.HeatNumber into grp
from innerRow in grp
select new {
innerRow.HeatNumber,
innerRow.ChargeNumber,
innerRow.Weight,
Percent = 100.0 * innerRow.Weight / grp.Sum(dd => dd.Weight)
};

他们都打印了这个结果:

HeatNumber    ChargeNumber     Weight  Percent 
1 1 500 8.06451612903226
1 2 3500 56.4516129032258
1 3 2200 35.4838709677419
2 1 2000 64.5161290322581
2 2 1100 35.4838709677419

这就是你想要的吗?为了简单起见,我省略了按日期过滤,因为真正的问题是在那之后出现的

关于c# - Linq to sql计算查询中一组项目的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com