DarthVader
DarthVader

Reputation: 55022

Grouping by date then sum

I have the following model:

public class MonthReport
{
    public int Id { set; get; }
    public DateTime MonthYear { set; get; }
    public int LateEntry { set; get; }
    public int LeftEarly { set; get; }
    public int TotalAttandence { set; get; }
    public int Great { set; get; }
    public int PersonelId { set; get; }
    public Personel Personel { set; get; }
}

Which maps to db with code first.

I want to group, reports by month, and year, then I want to get the sums for that particular month for LateEntry, LeftEarly, and other int values.

I have the following snippet which fails to return correct stuff.

    public ActionResult GetReportsGroupedByMonth()
    { 
        var results = _db.MonthReports
                         .GroupBy(
                            x => new
                            {
                                Month = x.MonthYear.Month,
                                Year = x.MonthYear.Year
                            }, 
                            (key, g) => 
                                new ChartModel
                                {
                                    Date = g.Select(v=>v.MonthYear).FirstOrDefault(),
                                    GreatDay = g.Select(e=>e.Great).Sum(),
                                    LateEntry = g.Select(e => e.LateEntry).Sum(),
                                    LeftEarly = g.Select(e => e.LateEntry).Sum(),
                                    TotalAttendance = g.Select(e => e.LateEntry).Sum(),
                                });

        return Json(results, JsonRequestBehavior.AllowGet);
    }

In result set, the values are same.

What s the problem here?

Thanks.

Upvotes: 0

Views: 85

Answers (1)

Jeremy Wiggins
Jeremy Wiggins

Reputation: 7299

I think it's just a copy/paste fail. You selected/summed e.LateEntry for 3 properties in your ChartModel.

Consider changing


new ChartModel
    {
        Date = g.Select(v=>v.MonthYear).FirstOrDefault(),
        GreatDay = g.Select(e=>e.Great).Sum(),
        LateEntry = g.Select(e => e.LateEntry).Sum(),
        LeftEarly = g.Select(e => e.LateEntry).Sum(),
        TotalAttendance = g.Select(e => e.LateEntry).Sum(),
    });

to


new ChartModel
    {
        Date = g.Select(v=>v.MonthYear).FirstOrDefault(),
        GreatDay = g.Select(e=>e.Great).Sum(),
        LateEntry = g.Select(e => e.LateEntry).Sum(),
        LeftEarly = g.Select(e => e.LeftEarly).Sum(),
        TotalAttendance = g.Select(e => e.TotalAttendance).Sum(),
    });

Upvotes: 1

Related Questions