2011-10-19 106 views
2

我是在LINQ-to-SQL中編寫查詢,並且在此查詢中是Date列。我想按照「周」對結果進行分組。我如何在LINQ到SQL中執行此操作?LINQ-to-SQL - 按日期分組的日期對象

由於

+1

這可能是你以後的事情; http://stackoverflow.com/questions/1059737/group-by-weeks-in-linq-to-entities – WooHoo

+2

一年中的哪一週?每月中的哪一週?星期幾? –

+2

我認爲最簡單的解決方案是從UDF調用datepart –

回答

3

假設公曆,「第一天」周規則,並且星期的第一天是星期一。

第一天星期規則:

表示一年中的第一週的 的第一天開始年份和 周以下指定的第一天之前結束

int firstDayOfWeek = (int)DayOfWeek.Monday; 
var q = 
    from u in TblUsers 
    let date = u.CreateDate.Value 
    let num = date.DayOfYear - 1 
    let num2 = ((int)date.DayOfWeek) - (num % 7) 
    let num3 = ((num2 - firstDayOfWeek) + 14) % 7 
    let week = (((num + num3)/7) + 1) 
    group u by week into g 
    select new 
    { 
     Week = g.Key, 
     Count = g.Count() 
    }; 
0

希望這有助於:

var d1 = new DateTime(1990, 1, 1); 
    var d2 = new DateTime(1990, 1, 2); 
    var d3 = new DateTime(1990, 1, 11); 
    var d4 = new DateTime(1990, 1, 12); 

    var records = new[] { 
     new { date = d1, freq = 1 }, 
     new { date = d2, freq = 2 }, 
     new { date = d3, freq = 3 }, 
     new { date = d4, freq = 4 } 
    }; 

    //ticks * WeekDays * DayHours * HourMins * MinSecs 
    var weekTicks = (Int64)10000000 * 7 * 24 * 60 * 60; 
    var res = records.GroupBy(x => x.date.Ticks/weekTicks) 
      .Select(x => new { week=x.Key ,sum=x.Sum(y=>y.freq)}); 

而這是結果:

[0] = {周= 99085,總和= 3}

[ 1] = {week = 99086,sum = 7}