问题描述
我想使用linq到sql进行查询(首选vb.net,但c#示例将为表创建表中按字段分组的记录,并且datetime字段中的孔大于30分钟。我该表在某项工作的生命周期中定期添加记录,通常每两分钟一次,有时会丢失一段时间,该表保存同一日期范围内多个工作的记录,尽管我只添加了一个具有不同工作编号的记录突出显示此内容。该表格如下表所示。
解决方法
编辑: VB .NET,未经测试:
Dim jobs = New List(Of Job)() From {
New Job() With {
.Date = New DateTime(2020,10,1,0),.JobGroup = 1,.Value = 100
},New Job() With {
.Date = New DateTime(2020,2,.Value = 200
},4,.Value = 300
},7,.JobGroup = 2,.Value = 600
},40,.Value = 400
},42,.Value = 500
},9,.Value = 700
},49,.Value = 800
}
}
Dim gaps = jobs.OrderBy(Function(x) x.JobGroup).Skip(1).Zip(jobs,Function(c,p) New With {Key
.Current = c,Key
.Previous = p,Key
.Gap = (c.Date - p.Date).TotalMinutes
}).Where(Function(x) x.Gap >= 30 AndAlso (x.Current.JobGroup = x.Previous.JobGroup))
For Each gap In gaps
Console.WriteLine($"Job Group: {gap.Current.JobGroup},Gap (minutes): {gap.Gap},Value: {gap.Current.Value} ")
Next
End Sub
Class Job
Public Property JobGroup As Integer
Public Property Date As DateTime
Public Property Value As Integer
End Class
我对VB有点生疏,所以我会像您说的那样给您C#答案。
//Sample Data //Year,Month,Day,Hour,Minute,Second,Millisecond
var jobs = new List<Job>() { new Job() { Date = new DateTime(2020,JobGroup = 1,Value = 100},new Job() { Date = new DateTime(2020,Value = 200},Value = 300},JobGroup = 2,Value = 600},Value = 400},Value = 500},Value = 700},Value = 800}
};
//Determine gaps
var gaps = jobs.OrderBy(x => x.JobGroup) //don´t mix job group IDs
.Skip(1) //To compare current and previous job record
.Zip(jobs,(c,p) => new { Current = c,Previous = p,Gap = (c.Date - p.Date).TotalMinutes }) //Determine gap between current and previous record
.Where(x => x.Gap >= 30 && (x.Current.JobGroup == x.Previous.JobGroup)); //Only take those gaps which are GT 30 minutes
foreach(var gap in gaps)
{
Console.WriteLine($"Job Group: {gap.Current.JobGroup},Value: {gap.Current.Value} ");
}
//Result:
//Job Group: 1,Gap(minutes): 36,Value: 400
//Job Group: 2,Gap(minutes): 40,Value: 800
我的样本数据只是一个简单的DTO
class Job
{
public int JobGroup { get; set; }
public DateTime Date { get; set; }
public int Value { get; set; }
}
,
请注意,@ Alex B的解决方案要求在执行之前将表拉入内存,因为.Zip无法转换为SQL。在这种情况下,您可能希望通过利用SQL's Lag...Over syntax的视图来研究此问题,而只是通过Linq to SQL Entity消耗其结果。像这样:
CREATE VIEW vwJobGaps AS
SELECT Job,DateAdded,PrevDateAdded,Value,DATEDIFF(m,DateAdded) As MinutesFromLastJob
FROM
(SELECT Job,LAG(DateAdded,null) over (Partition by Job order by DateAdded ASC) As PrevDateAdded
FROM MYTable))
然后针对您的实体:
<Table("vwJobGaps")>
Public Class JobGap
Public Property Job As Integer
Public Property DateAdded As DateTime
Public Property PrevDateAdded As DateTime
Public Property Value As Decimal
Public Property MinutesFromLastJob As Integer
End Class
由于您在此处使用视图,因此可以像使用其他表一样,使用标准LINQ向SQL添加其他过滤器,联接等:
var query = from gap in dc.JobGaps
where gap.MinutesFromLastJob > 30
'' select clause not needed in vb