将SQL查询转换为LINQ - DateDiff函数

时间:2016-03-09 09:12:59

标签: c# sql-server vb.net linq

我的任务是使用Groupby,Orderby,Date函数将以下SQL查询转换为LINQ。

SELECT 
       sd.name, s.BuilderName,
       Min(Date) as MinDatetime, 
       Max(Date) as MaxDatetime, 
       datediff(day, min(Date), max(Date))/ cast (count(sd.jobRobosname) as float) 
FROM 
       [Data] sd  
JOIN Example s ON s.name= sd.Name
WHERE jobRobosjobid='NOT RUN' 
GROUP  BY sd.name, s.name

我试过了,

(from record in _db.Data                              
join jobRobos in _db.Example on record.Name equals Example.Name
where record.jobRobos jobid != "NOT RUN"
  group jobRobos by new {record.Name,jobRobos .BuilderName} into r
select new
{
    jobRobos Name = r.Key.jobRobos Name,
    BuilderName = r.Key.BuilderName,
    MaxDate = r.Key.Min(r.Date),
    MinDate = r.Max(c => c.Date),
    Diff = r.Key.datediff(day, MinDate, MaxDate) / r.Key.Cast(Count(r.Key.jobRobos Name) as float)
}).ToList();

我在这里提到了一些类似的问题:

但找不到解决方案。

有人能建议我一些想法吗?

1 个答案:

答案 0 :(得分:1)

使用EF 6,这应该可以使用DbFunctions.DiffDays

(from record in _db.Data                              
join spider in _db.Example on record.Name equals Example.Name
where record.spiderjobid != "NOT RUN"
  group spider by new {record.Name,spider.BuilderName} into r
select new
{
    Name = r.Key.Name,
    BuilderName = r.Key.BuilderName,
    MaxDate = r.Max(d => d.Date),
    MinDate = r.Min(d => d.Date),
    Diff = DbFunctions.DiffDays(r.Max(d => d.Date), r.Min(d => d.Date)) / r.Count(d => d.SpiderName)
}).ToList();