[英]How to create a new field that returns true or false on the difference between two records using row_number
I have a railroad crossing database table that has columns CrossingID
, ReasonID
, and LastUpdated
on top of a lot of additional columns.我有一个铁路道口数据库表,在许多附加列的顶部有列
CrossingID
、 ReasonID
和LastUpdated
。
Each CrossingID
has several records going back through time for each time the database was updating that crossing.每个
CrossingID
都有几条记录,每次数据库更新该交叉点时都会回溯。 I want to take the latest two records per CrossingID
, order them by LastUpdated
, and create a new field that spots any differences between the other fields and returns a true or false.我想获取每个
CrossingID
的最新两条记录,按LastUpdated
它们进行排序,并创建一个新字段,以发现其他字段之间的任何差异并返回 true 或 false。
I figured out how to do the groupings with row_number and using a with statement as I just do not know how to create the checking field for any differences.我想出了如何使用 row_number 进行分组并使用 with 语句,因为我不知道如何为任何差异创建检查字段。 Here is what I got so far:
这是我到目前为止所得到的:
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY crossingid ORDER BY lastupdated DESC) AS RowNo,
crossingid, lastupdated, reportstatus, reasonid
FROM
statecrossingdata_5year
)
SELECT
crossingid, lastupdated, rowno, reportstatus, reasonid
FROM
cte
WHERE
rowno <= 2
ORDER BY
crossingid, rowno
The Railroad database is public records and can be found here: https://safetydata.fra.dot.gov/OfficeofSafety/publicsite/DownloadCrossingInventoryData.aspx铁路数据库是公共记录,可在此处找到: https : //safetydata.fra.dot.gov/OfficeofSafety/publicsite/DownloadCrossingInventoryData.aspx
Something along these lines沿着这些路线的东西
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY crossingid ORDER BY lastupdated DESC) AS RowNo,
crossingid, lastupdated, reportstatus, reasonid
FROM
statecrossingdata_5year
),
CTE2 as
(
SELECT
crossingid, lastupdated, rowno, reportstatus, reasonid
FROM
cte
WHERE
rowno <= 2
)
SELECT x.*,
CASE WHEN x.reasonID = y.reasonID THEN 'TRUE' ELSE 'FALSE' END
FROM CTE2 x
INNER JOIN CTE2 y
ON x.crossingID = y.crossingID
WHERE X.rowno = 2 AND y.rowno = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.