我正在尝试找到一种获取结果的方法,其中最新Occupancy
中的Inspection_date
与最后一个之前的RoomID
不相等。
在此示例中,只有数字Occupancy
2才是唯一的结果,因为:OrderID
的{{1}} 201 ='空缺' <>到Occupancy
的{{1}} 202 ='被占用'。
我有查询的开头,但似乎找不到一个好的逻辑来结束查询。
OrderID
答案 0 :(得分:1)
在SQL Server 2012+中,您可以使用lag()
,如下所示:
SELECT i.*
FROM (SELECT i.room_number, order_number, Occupancy ,
ROW_NUMER() OVER (PARTITION BY room_number ORDER BY Inspection_date DESC) as seqnum,
LAG(Occupancy) OVER (PARTITION BY room_number ORDER BY Inspection_date) as prev_Occupancy
FROM #inspection_data i
) i
WHERE prev_Occupancy <> Occupancy AND seqnum = 1 ;