我在项目中使用LINQ to SQL,我在同时执行join
和group by
时遇到问题,需要对每个表中的两个字段进行比较。
以下是我的查询:
var q =
(from ii in
(from a in table1
join b in table2 on a.BudgetUnitID equals b.BudgetUnitID
select new { BT = a.Amount, BA = b.Amount, BUID = a.BudgetUnitID, BU = a.BudgetUnit.BudgetUnitName })
group ii by new {ii.BUID} into g
select new
{
BudgetUnit = g.Key,
Budget = g.Sum(x => x.BA),
Actual = g.Sum(x => x.BT),
Variance = g.Sum(x => x.BA) - g.Sum(x => x.BT)
}).ToList();
我要将其绑定到网页上的网格视图。我的问题是我没有在其中一列上得到正确的总数。
非常感谢您的帮助。
答案 0 :(得分:2)
您的问题很可能是预算金额不正确,因为您要为每个组合汇总它们。例如,如果您的预算数据如下所示:
Budget | Amount
Dev | 2500
这样的订单项:
Budget | Amount
Dev | 1000
Dev | 750
然后你在内部查询中将它们组合在一起,如下所示:
BA | BT
2500 | 1000
2500 | 750
然后将它们汇总在一起,这会给你
Budget | Actual
5000 | 1750
在这种情况下,预算是应有的两倍,因为您要为每个组合添加所有条目。在将结果连接在一起之前,您希望首先对各个表进行求和,这样您的子查询数据就不会出现这种“重复”问题:
var q =
(from ii in
(from a in table1 group a by a.BudgetUnitID into g
select new { BudgetUnitID = g.Key, Amount = g.Sum(x => x.Amount) })
join jj in
(from b in table2 group b by b.BudgetUnitID into g
select new { BudgetUnitID = g.Key, Amount = g.Sum(x => x.Amount) })
on ii.BudgetUnitID equals jj.BudgetUnitID
select new { Actual = ii.Amount, Budget = jj.Amount, Variance = jj.Amount - ii.Amount, BUID = ii.BudgetUnitID }
).ToList();