首页 > 解决方案 > 嵌套 IIF 和 ISNULL 以返回最后一条记录

问题描述

我正在尝试获取此设备历史记录的查询,以用该设备的最后记录位置填充该设备的位置 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”插入空白单元格,这是向前迈出的一步,但我一直在试图弄清楚如何让它显示最后记录的位置 ID。

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

标签: sqlms-accessrelational-database

解决方案


我能够通过重组我的数据以使其连接更加简单来解决这个问题。我意识到了这一点,[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

推荐阅读