I have a database table of events. Each event has a category and a date/time.
(actually events have sub-categories which are contained in categories and various other properties, left out in this simplified example)
I want to generate a list with an entry for each hour and category, listing the number of events and their percentage.
date | category | number of events | percentage
----------------------------------------------------------
2012-01-01 1:00 | cat-1 | 10 | 50%
2012-01-01 1:00 | cat-2 | 10 | 50%
2012-01-01 2:00 | cat-1 | 1 | 10%
2012-01-01 2:00 | cat-2 | 9 | 90%
2012-01-01 3:00 | cat-1 | 3 | 100%
...
I am having trouble calculating the percentage efficiently. Here is what I have so far:
var results = datacontext.events.
groupBy(e=>new
{ // group by category and hour
category = e.category,
datetime = new DateTime (
e.datetime.Year, e.datetime.Month, e.datetime.Day,
e.datetime.Hour, 0, 0 )
// use date+hour for grouping, ignore minutes/seconds
}).
select(group => new
{
category = group.Key.category,
datetime = group.Key.datetime,
numberOfEvents = group.count(),
percentage = group.count() / ["total number of events for this hour"] * 100.0
}
How can I get the value for [total number of events for this hour], ideally in an elegant and efficient way?