3

我有以下数据表:

[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

如何实现这个目标?

4

2 回答 2

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,尽管它现在取决于您的 Time 列通过 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()
于 2012-09-24T11:30:34.287 回答
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()
    }
于 2012-09-24T11:43:11.520 回答