I am using LINQ to SQL in a project and I am having an issue doing both a join and a group by to do a comparison between the two fields that are in each table.
Here is what my query looks like:
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();
I am am going to bind this to a grid view on a web page. My problem is that I am not getting the totals correct on one of the columns.
Your help is much appreciated.
Your problem is likely that the Budget amount is incorrect, because you are summing them for every combination. For example, if you had budget data looking like this:
And line items like this:
Then you are combining them together in your inner query like this:
And then summing them together, which gives you
In this case, the budget is twice as large as it should be, because you are adding all the entries together per combination. You want to sum the individual tables first, before joining the results together so that you don’t have this “duplication” issue in your sub-query data: