0

我正在尝试将此查询放入 Linq

SELECT [ID], [Name], LastSync, Phase
FROM [Store] 
LEFT JOIN (
    SELECT GLog.[StoreId] AS [StoreId], LastSync, Phase
    FROM [GGCSyncLog] AS GLog 
    INNER JOIN (
        SELECT MAX(G1.[DateTime]) AS LastSync, G1.[StoreId]
        FROM [GGCSyncLog] AS G1
        GROUP BY G1.[StoreId]
        ) AS G2 ON (GLog.[StoreId] = G2.[StoreId]) AND (GLog.[DateTime] = G2.[LastSync])
    ) AS MostRecentLog ON Store.[ID] = MostRecentLog.[StoreId]

其结果是

ID  Name                 LastSync     Phase
1   Sarasota             2010-07-31   5
2   Wellington           2010-07-31   8
3   Tampa International  2013-03-12   8
5   Events               NULL         NULL
6   PO Holding Store     NULL         NULL

我的 Linq 返回正确的结果,除了我缺少 LastSync 和 Phase 为空的两行。知道有什么问题吗?

from s in Stores
join gLog in 
(from g1 in GGCSyncLogs.DefaultIfEmpty()
join g in 
(from g in GGCSyncLogs
group g by g.StoreId into gM
   select new {
   StoreId = gM.Key, LastSync = gM.Max(gg=>gg.DateTime) })
   on new {g1.StoreId, LastSync = g1.DateTime} equals new {g.StoreId,  g.LastSync}
     select new {g1.StoreId, g.LastSync, g1.Phase})
     on s.ID equals gLog.StoreId
        select new {s.ID, s.Name, 
            LastSync = (gLog != null ? (DateTime?)gLog.LastSync : null), 
            Phase = (gLog != null ? (int?)gLog.Phase : null) }
4

2 回答 2

0

您应该阅读 aboutjoin子句How to: Perform Left Outer Joins

在没有数据库的情况下很难找到有效的解决方案,但希望这能帮助您重回正轨:

var g2 = from g1 in GGCSyncLogs
         group g1 by g1.StoreId into gM;

var MostRecentLogs = from gLog in GGCSyncLogs
                     join g in g2 on new { gLog.StoreId, LastSync = gLog.DateTime} equals new { g.StoreId, g.LastSync }
                     select new { gLog.StoreId, LastSync = gLog.Date, Phase = gLog.Phase };

var results = from s in Stores
              join gLog in MostRecentLogs on s.Id equals gLog.StoreId into gl
              from l in gl.DefaultIfEmpty(new { LastSync = null, Phase = null })
              select new {
                  s.Id,
                  s.Name,
                  l.LastSync,
                  l.Phase
              };
于 2013-03-15T17:03:50.553 回答
0

我不得不使用“进入”

from s in Stores
join gRec in
(from g in GGCSyncLogs
join g2 in 
(from g1 in GGCSyncLogs
group g1 by g1.StoreId into gM
  select new {StoreId = gM.Key,LastSync = gM.Max(gg=>gg.DateTime)})
  on new {g.StoreId, LastSync = g.DateTime} equals new {g2.StoreId, g2.LastSync}
    select new {g.StoreId, g2.LastSync, g.Phase})
    on s.ID equals gRec.StoreId into gRec2
    from gRec3 in gRec2.DefaultIfEmpty()
    select new {s.ID, s.Name, 
                    LastSync = (gRec3 != null ? (DateTime?)gRec3.LastSync : null),
                    Phase = (gRec3 != null ? (int?)gRec3.Phase : null) }
于 2013-03-15T18:57:00.110 回答