sql - 嵌套 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]
表通过下拉列表引用)。我不确定它为什么这样做并且需要解决它,但至少我看到此时填充了空单元格。
解决方案
我能够通过重组我的数据以使其连接更加简单来解决这个问题。我意识到了这一点,[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
推荐阅读
- vue.js - 子目录上的 Nuxtjs
- ios - NSMutableDictionary 和 NSCache(复制与保留)之间处理密钥的不同方式是否会导致不同的结果?
- django - 如何使用 CKEDITOR_THUMBNAIL_SIZE = (500, 500) ckeditor django?
- javascript - TypeError:无法读取 null 的属性(读取“classList”)反应
- elasticsearch - 如何处理 search_as_you_type 字段和拼写错误
- typescript - 在 TypeScript 中引用 Vuetify
- c - 创建VI将结构从DLL导入LabVIEW时出现问题
- laravel - 如何在 Laravel 8 中将数据存储在具有不同属性的一张表中
- pytorch - Detectron2 VS MMDetection
- visual-studio-code - VSCode - Julia 设置 - 智能感知