以下 SQL 查询的 LINQ 等效项是什么?

时间:2021-06-22 12:29:06

标签: sql linq sql-to-linq-conversion

T-SQL 查询:

 SELECT  T1.ID, 
        T1.UserId,
        T1.ServerId,
        T1.DiskId, 
        T1.Date_ PreviousDate_, 
        T1.Row,
        MIN(T2.Date_) AS Date_, 
        DATEDIFF(MINUTE, T1.Date_, MIN(T2.Date_)) AS MinutesDiff
FROM    IesLogs T1
        LEFT JOIN IesLogs T2
            ON T1.DiskId = T2.DiskId
            where T1.DiskId = 2 AND T2.Date_ > T1.Date_ AND T1.Row = T2.Row
GROUP BY T1.ID,T1.UserId, T1.ServerId, T1.DiskId, T1.Date_, T1.[Row]
ORDER BY T1.DiskId, T1.[Row], T1.Id

enter image description here

我获得的数据比我预期的要多。

  var result = (
                    from i in context.IesLogs
                    join i2 in context.IesLogs 
                        on i.DiskId equals diskId into i2left
                    from i3 in i2left.DefaultIfEmpty()
                    where 
                        i.UserId == userId
                        && i3.Date > i.Date
                        && i.Row == i3.Row
                    group i3 by new {i.Id, i.ServerId,i.DiskId, i.Row, PreviousDate = i.Date, i3.Date} into logs
                    orderby logs.Key.DiskId, logs.Key.Row,logs.Key.Id  ascending
                    select new IesLogStatisticsDto
                    {
                        Id = logs.Key.Id,
                        ServerId = logs.Key.ServerId,
                        DiskId = logs.Key.DiskId,
                        PreviousDate = logs.Key.PreviousDate,
                        Date = logs.Min(x => x.Date),
                        Row = logs.Key.Row,
                        DateDiff = Convert.ToInt32((logs.Min(x => x.Date) - logs.Key.PreviousDate).TotalMinutes)
                    }).ToList();

我应该得到 6 个数据时却得到了 12 个。我该如何解决?

我认为我获得大量数据的原因是上面代码博客中的(i3.Date > i.Date) 但我必须实现这一行。

1 个答案:

答案 0 :(得分:1)

您的 LINQ 查询分组错误。您必须从分组键中删除 i3.Date

稍微重构:

var query =
    from i in context.IesLogs
    join i2 in context.IesLogs 
        on i.DiskId equals diskId into i2left
    from i2 in i2left.DefaultIfEmpty()
    where 
        i.UserId == userId
        && i2.Date > i.Date
        && i.Row == i2.Row
    group i2 by new {i.Id, i.ServerId, i.DiskId, i.Row, PreviousDate = i.Date} into logs
    orderby logs.Key.DiskId, logs.Key.Row, logs.Key.Id  ascending
    select new IesLogStatisticsDto
    {
        Id = logs.Key.Id,
        ServerId = logs.Key.ServerId,
        DiskId = logs.Key.DiskId,
        PreviousDate = logs.Key.PreviousDate,
        Date = logs.Min(x => x.Date),
        Row = logs.Key.Row,
        DateDiff = Convert.ToInt32((logs.Min(x => x.Date) - logs.Key.PreviousDate).TotalMinutes)
    };