Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by Week of year (Week number) in Linq to SQL

In regular SQL i could do something like

SELECT * From T GROUP BY DATEPART(wk, T.Date)

How can i do that in Linq to SQL ?

The following don't work

From F In DB.T Group R By DatePart(DateInterval.WeekOfYear, F.Date)

Also don't work:

From F In DB.T Group R By (F.Date.DayOfYear / 7)
like image 822
ariel Avatar asked Aug 06 '10 21:08

ariel


1 Answers

LINQ to SQL does not support the Calendar.WeekOfYear method, but you could potentially create a TSQL function that wraps the call to DatePart. The DayOfYear / 7 trick should work for most cases and is much easier to use. Here's the code I ended up with:

var x = from F in DB.T
        group F by new {Year = F.Date.Year, Week = Math.Floor((decimal)F.Date.DayOfYear / 7)} into FGroup
        orderby FGroup.Key.Year, FGroup.Key.Week
        select new {
            Year = FGroup.Key.Year,
            Week = FGroup.Key.Week,
            Count = FGroup.Count()
        };

Results in something like this:

Year    Week    Count
2004    46      3
2004    47      3
2004    48      3
2004    49      3
2004    50      2
2005    0       1
2005    1       8
2005    2       3
2005    3       1
2005    12      2
2005    13      2
like image 85
Greg Bray Avatar answered Oct 14 '22 11:10

Greg Bray