I have this table that I access throught linq-to-entities:
- Day
- Amount
- Type (1 or 2)
I have many rows on the same day and of the same type and I need to summarize their amounts by month. That’s easy:
from r in rows
group r by new { r.Date.Year, r.Date.Month }
into g
select
new
{
Date = new DateTime(g.Key.Year, g.Key.Month, 1),
Hours = g.Sum(a => a.Amount)
};
However, I have a special rule that I need to implement in the same LINQ, that I would like some help with:
If there is ANY type 2 on a given day, then THAT day should only sum of type 2. Otherwise it should summarize on type 1.
Notice that the distinction between type 1 and type 2 is per day and the sum is per month.
UPDATE
As I’m dealing with a LOT of data, I need to get it all in one database call, I cannot load it into memory and manage it there.
Ratio behind this is very simple: the requirement “if there’s at least one type 2 record, sum only type 2 records” can be implemented by simply grouping records by type (within days, of course). Why does it work? Because we split all records into two groups, type 2 (which should be used if there is at least one type 2 record), and type 1 (which in fact means “all records when no type 2 present”). Second part (choosing sum) is even simpler: we just order groups (within day) by descending type (i.e. sum for type 2, sum for type 1) and take first one, which gives us type 2 if present and type 1 otherwise.
Frankly, it’s a kind of “smart code” everybody hates, because nobody could understand from a glance how it works.