Linq:按时间间隔分组

时间:2012-09-24 10:07:20

标签: vb.net linq time intervals linq-group

我有以下数据表:

[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:

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

如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

以下是针对Linq-to-SQL(在SQL Server上)的解决方案,其中DateTime位于单个字段中(LINQpad查询):

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()

答案 1 :(得分: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()
    }