I have a array of analytic events in my database and i would like to send this data grouped by date to my client app.
The data from the db looks something like this (but with hundreds of records):
[
{
"DateAdded": "2006-12-30 00:38:54",
"Event": "click",
"Category": "externalWebsite"
},
{
"DateAdded": "2006-07-20 00:36:44",
"Event": "click",
"Category": "social"
},
{
"DateAdded": "2006-09-20 00:36:44",
"Event": "click",
"Category": "social"
},
{
"DateAdded": "2006-09-22 00:12:34",
"Event": "load",
"Category": "profile"
}
]
What I would like to do is return the count of all the say 'social' 'click' but by month so it would look like this:
[
{
"name": "socialclicks",
"series": [
{
"count": 259,
"name": "Jan"
},
{
"count": 0,
"name": "Feb"
},
{
"count": 52,
"name": "Mar"
}
... etc, etc up to Dec <====
]
}
]
So, what I have been trying is to get all the records that are associated with a particular user using their id. This is simple.
Now I need to split them records into monthly counts showing the last 12 months from the current month (if the month doesn't exist return 0) - this is proving to be complicated and difficult.
My approach was this:
var records = context.records.where(r => r.Id = userId).ToList();
var jan
var feb
var mar
var apr
... etc, etc
for (int i = 0; i < records.Count ; i++)
{
if (record.DateAdded > "2005-12-31 00:00.00" && record.DateAdded < "2006-01-31 00:00.00") {
jan++;
}
if (record.DateAdded > "2006-01-31 00:00.00" && record.DateAdded < "2006-02-28 00:00.00") {
feb++;
}
...etc, etc
}
Then i use these variables to count and hard code the name for the returned data.
As you can see, there is lots of etc, etc because the code has become ridiculous!
There must be a more simple way to do this but i cant seem to find one!
Any assistance would be appreciated.
Thanks