2012-09-24 61 views
3

我有以下數據表:的Linq:集團按時間間隔

[Date];[Time];[ProcessID];[ID] 
24.09.2012;08:18:00;4000;1 
24.09.2012;08:18:00;4000;2 
24.09.2012;08:19:00;4001;3 
24.09.2012;08:23:00;4002;4 
24.09.2012;08:32:00;4003;5 
... 

至於結果,我想有一個15分鐘的時間間隔分組計數ProcessID's:

[Interval];[ProcessID Count] 
8:15:00 - 8:29:00;3 
8:30:00 - 8:45:00;1 

如何實現這一目標?

+3

是'類型的Date''Date'和'類型的時間...?爲什麼不使用一列而是兩列呢?你有什麼嘗試?如果可能的話,你應該在dbms中做。 –

+0

是,日期列是一個日期類型和時間列是時間類型。我必須處理這個問題,因爲它是由我的erp軟件提供的。 – user1434532

+1

什麼是「時間」類型?我只知道'TimeSpan' –

回答

1

下面是與日期時間在一個單一的領域之中(LINQpad查詢)對LINQ到SQL(上SQL Server)的解決方案:

Const BaseDate As Date = #9/24/2012# 
Const PeriodMinutes As Integer = 15 
Dim p = From t In TestData _ 
     Group By q=CInt(Math.Floor((t.SomeDate - BaseDate).TotalMinutes/PeriodMinutes)) Into Group _ 
     Select s=BaseDate.AddMinutes(q*PeriodMinutes), _ 
      e=BaseDate.AddMinutes((q+1)*PeriodMinutes), _ 
      ids=Aggregate g In Group Select g.ProcessID Distinct Into Count() 
p.Dump 

使用不同類型和其他「小」的調整可能產生更簡單的SQL後端代碼。

對於您的實際數據庫,您需要調整Group By,儘管它現在取決於您的時間列通過Linq-to-SQL和/或數據庫的驅動程序轉換爲什麼。

由於它是一個TimeSpanGroup By變成類似:

Group By d=t.[Date], q=CInt(Math.Floor(t.[Time].TotalMinutes/PeriodMinutes)) Into Group _ 
    Select s=d.AddMinutes(q*PeriodMinutes), _ 
      e=d.AddMinutes((q+1)*PeriodMinutes), _ 
      ids=Aggregate g In Group Select g.ProcessID Distinct Into Count() 
+0

偉大的作品! – user1434532

1

這應該工作( 然而,沒有測試 ):

Dim groupedByQuarter = 
    From r In table 
    Let day = r.Field(Of Date)("Date").Date 
    Let time = r.Field(Of TimeSpan)("Time") 
    Let quarter = time.Add(TimeSpan.FromMinutes((-1) * time.Minutes Mod 15)) 
    Group r By Key = New With {Key .day = day, Key .quarter = quarter} Into TimeGroup = Group 
    Select New With { 
     .Interval = String.Format("{0} - {1}", 
       Key.quarter, 
       Key.quarter.Add(TimeSpan.FromMinutes(14))), 
     .ProcessCount = TimeGroup.Select(Function(r) r.Field(Of Int32)("ProcessID")).Distinct().Count() 
    } 
+0

您的解決方案也適用。非常感謝你! – user1434532