将 IIF 和 ISNULL 嵌套到 return 最后一条记录

Nesting IIF and ISNULL to return last record

我正在尝试查询设备的历史记录,以使用其最后记录的位置填充该设备的位置 ID,但我无法弄清楚如何让它以这种方式工作。

初始结果

想要的结果

想法是,如果没有安装或删除记录,则位置与该设备的最后记录中的位置相同。上面的屏幕截图来自于尝试实现此目的之前。

SELECT 
    ns.online, 
    n.[node serial number], 
    ns.gateway, 
    ns.[date verified], 
    nls.[location id],
    IIF (ISNULL(nls.[location id]),"null",nls.[location id]) AS [location status],
    nls.[install/remove], 
    nls.[date of action], 
    tbm.[TBM-R], 
    tbm.[TBM-L],
    ns.notes
FROM 
    (
        (nodes AS n INNER JOIN 
        [node status] AS ns ON n.nodeid = ns.[node serial]) LEFT JOIN 
        [node location status] AS nls ON (ns.[node serial] = nls.[node serial number]) AND 
        (ns.[date verified] = nls.[date of action])) LEFT JOIN 
        [TBM Station] AS tbm ON ns.[Date Verified] = tbm.[Date Reported]
WHERE 
    n.[node serial number]=[Enter node serial number]
ORDER BY 
    [date verified] DESC

当前结果

正如您所看到的,我已经设法将 "null" 插入到空白单元格中,这是向前迈出的一步,但我一直在努力弄清楚如何让它显示最后记录的内容位置编号。

12和13指的是位置table中正确位置id的记录id(不是在查询中直接引用,而是[node location status] table通过drop引用吃下)。我不确定它为什么这样做,需要解决这个问题,但至少我看到此时填充了空单元格。

我能够通过重组我的数据以简化连接来解决这个问题。我意识到 [Node Location Status][Node Status] 不必分隔表。执行此操作后,以下查询能够按照我想要的方式显示位置状态。

    [Node Status].Online, 
    [Node Status].[Not in Service], 
    Nodes.[Node Serial Number], 
    [Node Status].Gateway, 
    [Gateway Status].Online, 
    [Node Status].[Location Status], 
    [Node Status].[Install/Remove], 
    [Node Status].[Date Verified], 
    [TBM Station].[TBM-L], 
    ([TBM Station].[TBM-L])-(Locations.Station) AS [TBM L], 
    ([TBM Station].[TBM-R])-(Locations.Station) AS [TBM R], 
    [Node Status].Notes
FROM 
    Locations RIGHT JOIN 
    (((Nodes INNER JOIN [Node Status] ON Nodes.NodeID = [Node Status].[Node Serial]) INNER JOIN 
    [TBM Station] ON [Node Status].[Date Verified] = [TBM Station].[Date Reported]) LEFT JOIN 
    [Gateway Status] ON [Node Status].[Date Verified] = [Gateway Status].Updated) ON Locations.LocationID = [Node Status].[Location Status]
WHERE 
    (((Nodes.[Node Serial Number])=[Enter node serial number]))
ORDER BY 
    [Node Status].[Date Verified] DESC