TSQL:条件查询

时间:2016-09-30 23:54:02

标签: sql sql-server tsql where

我正在尝试找到一种获取结果的方法,其中最新Occupancy中的Inspection_date与最后一个之前的RoomID不相等。

在此示例中,只有数字Occupancy 2才是唯一的结果,因为:OrderID的{​​{1}} 201 ='空缺' <>到Occupancy的{​​{1}} 202 ='被占用'。

我有查询的开头,但似乎找不到一个好的逻辑来结束查询。

OrderID

1 个答案:

答案 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 ;