LINQ查询日期出现次数

时间:2016-03-11 05:13:19

标签: c# linq

我需要将此SQL查询转换为LINQ查询。

SQL:

SELECT  Name,
        Date,
        NextDate,
        DATEDIFF("D", Date, NextDate)
FROM    (   SELECT    Name,    

                    Date,
                    (   SELECT  MIN(Date) 
                        FROM    DailyJobCount T2
                        WHERE   T2.Name = T1.Name
                        AND     T2.Date > T1.Date AND T2.id ='NOT RUN' AND T1.id ='NOT RUN'
                    ) AS NextDate
            FROM    DailyJobCount T1   
        ) AS T  
        where Date >= '03-03-2015' and Date <='03-03-2016' 
        group by T.Name, Date,NextDate 

我试过了,

 var deviation = (from record in _db.DailyJobCount
    where
        record.Date >= StartTime && record.Date <= EndTime && record.IsActive.Equals(true) &&
        record.jobid == "NOT RUN"
    group new {record} by new
{
    record.Name, record.Date
}
into rec
    select new
    {
        Name = rec.Key.Name,
        Diff = SqlFunctions.DateDiff("day",StartTime, NextDate ),


    }
    );

但是它在“NextDate”中给出了错误,也没有完成LINQ QUery。我真的不知道这个。你能否就这个问题提出建议。非常感谢.Anyhelp。

由于

1 个答案:

答案 0 :(得分:1)

您可以尝试以下变体:

<强> LINQ:

var dateFrom = new DateTime(2015, 03, 03);
var dateTo = new DateTime(2016, 03, 03);
var id = "NOT RUN";

var query = from item1 in _db.DailyJobCounts
            where item1.Date >= dateFrom && item1.Date <= dateTo
            from item2 in _db.DailyJobCounts
            where item1.Name == item2.Name && item1.Date < item2.Date && item1.id == id && item2.Name == id
            group new { item1, item2 } by new { item1.Name, item1.Date } into subGroup
            select new
            {
                subGroup.Key.Name,
                subGroup.Key.Date,
                NextDate = subGroup.Min(x => x.item2.Date),
            } into result                        
            select new
            {
                result.Name,
                result.Date,
                result.NextDate,
                Diff = SqlFunctions.DateDiff("day", result.Date, result.NextDate),
            };

var answer = query.ToList();

<强> T-SQL:

SELECT 
    1 AS [C1], 
    [GroupBy1].[K2] AS [Name], 
    [GroupBy1].[K1] AS [Date], 
    [GroupBy1].[A1] AS [C2], 
    DATEDIFF(day, [GroupBy1].[K1], [GroupBy1].[A1]) AS [C3]
    FROM ( SELECT 
        [Extent1].[Date] AS [K1], 
        [Extent1].[Name] AS [K2], 
        MIN([Extent2].[Date]) AS [A1]
        FROM  [dbo].[DailyJobCounts] AS [Extent1]
        INNER JOIN [dbo].[DailyJobCounts] AS [Extent2] ON ([Extent1].[Name] = [Extent2].[Name]) OR (([Extent1].[Name] IS NULL) AND ([Extent2].[Name] IS NULL))
        WHERE ([Extent1].[Date] >= 03.03.2015 0:00:00) AND ([Extent1].[Date] <= 03.03.2016 0:00:00) AND ([Extent1].[Date] < [Extent2].[Date]) AND ([Extent1].[id] = 'NOT RUN') AND (([Extent2].[Name] = 'NOT RUN') OR (([Extent2].[Name] IS NULL) AND ('NOT RUN' IS NULL)))
        GROUP BY [Extent1].[Date], [Extent1].[Name]
    )  AS [GroupBy1]