2014-02-28 57 views
0

Grouping records hour by hour or day by day and filling gaps with zero or nullGrouping records hour by hour or day by day and filling gaps with zero or null in mysql之前有類似的問題,但兩個solutuion都使用SQL。我想用代碼解決這個問題。在Enity中按小時分組的記錄框架和填充間隙

最簡單的方法是運行:

var q = from i in XXX.Table 
    let dt = p.Date 
    group i by new { y = dt.Year, m = dt.Month, d = dt.Day, h = dt.Hour} 
    select g; 

,但我有一個很大的差距仍然填補。

+0

這是查詢將要組合成另一個查詢,或者我們可以認爲這(和已填寫的空白)將要物化?換句話說,服務器是否必須生成填充? – casperOne

+0

您的實體框架可以將p.Date轉換爲SQL嗎? –

+0

@casperOne我喜歡用這個查詢作爲子查詢,所以答案是肯定的,服務器應該生成填充 –

回答

0

您可以獲取從服務器組和客戶填補空白:

var startDate = new DateTime(2014, 1, 2); 
var endDate = new DateTime(2014, 1, 3); 

var dict = (from c in YourTable 
    where c.YourDate >= startDate && c.YourDate <= endDate 
    let hours = DbFunctions.DiffHours(startDate, c.YourDate) 
    group c by hours into g 
    select new {Hour = g.Key, Count = g.Count()}).ToDictionary(r => r.Hour.Value, r => r.Count); 

var result = Enumerable.Range(0, (int)(endDate - startDate).TotalHours).Select(h => new {Date = startDate.AddHours(h), Count = dict.ContainsKey(h) ? dict[h] : 0});