首页 > 解决方案 > 帽子是以下 SQL 查询的 LINQ 等价物吗?

问题描述

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

在此处输入图像描述

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

  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上面代码博客中的(),但我必须实现这一行。

标签: sqllinqsql-to-linq-conversion

解决方案


您的 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)
    };

推荐阅读