我有以下数据表:
[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 分钟的时间间隔进行分组以计算进程 ID:
[Interval];[ProcessID Count]
8:15:00 - 8:29:00;3
8:30:00 - 8:45:00;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 和/或数据库驱动程序将"时间"列转换为的内容。
由于它是TimeSpan
,因此Group 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()
这应该有效(但是,未经过测试):
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()
}