我目前面临的挑战是获取按特定字段对行进行分组的行的总和,然后将结果返回到每个单独的行。
我想做的小组是客户&集团&年份并获得金额和月份的金额。
下面是数据集的示例,右边的2列是我要添加的列:
private void button1_click(object sender, eventsargs e)
{
bool Found = false;
if (datagridview1.rows.count > 0)
{
foreach (datagridview row in datagridview1.rows)
{
if (Convert.ToString(row.cells[0].Value) == cmbproductname.text && convert.tostring(row.cells[1].value) == textprice.text)
{
row.cell[2].value = convert.tostring(1 + convert.toint16(row.cells[2].value));
Found = true;
}
}
if (!Found)
{
datagridview1.rows.add(cmbproductname.text, txtprice.text, 1);
}
}
else
{
datagridview1.rows.add(cmbproductname.text, txtprice.text, 1);
}
}
我目前的代码结构如下:
Client Group Year Amount Months Sum(Amount) Sum(Months)
Client1 Group1 Current Year 100 3 300 10
Client1 Group1 Current Year 200 7 300 10
Client2 Group1 Year-1 150 1 400 3
Client2 Group1 Year-1 250 2 400 3
Client3 Group1 Year-2 500 11 500 11
Client3 Group2 Year-3 600 12 600 12
因此想要添加交叉申请:
Select
Data.Client, data.Group, Calc_field2.Year, data.Amount, Calc_field.Months
From
(Select [Column adjustments] From [Source] where [criteria]
Union ALL
Select * from [Source#2] where [Criteria]
) as Data
Cross Apply
(Data.[End Date] - Data.[Start Date]) as Calc_Field(Months)
[Rolling Year formula from Data] as Calc_Field2(Year)
然后将其添加到主要部分
Cross Apply
(Select
Data.Client, Data.Group, Calc_field2.Year,
SUM(Data.Amount) as 'SUM Amount',
SUM(Calc_Field.Months) as 'SUM Months'
Group by
Data.Client, Data.Group, Calc_field2.Year
) as MONTH_AMOUNT_SUM
我有一种感觉它不会起作用,这可以通过以下方式得到证实:
每个GROUP BY表达式必须至少包含一个不是外部引用的列。
有人会有什么建议可以采取最佳方法吗?
谢谢你, 卢卡斯
答案 0 :(得分:0)
使用窗口功能。更改的唯一部分是select
:
select Data.Client, data.Group, Calc_field2.Year, data.Amount, Calc_field.Months,
sum(data.amount) over (partition by data.client, data.group, calc_field2.year),
sum(data.months) over (partition by data.client, data.group, calc_field2.year)