我有一个数据库,我希望获得当前的房间号码和以前的房间号码。
数据看起来像这样。 表X
Name, room_number, Start_Date, End_Date, status
Bob, A1, 2015-04-03, null, transfer
Bob, B5, 2013-04-15, 2015-04-03, somestatus
Bob, B7, 2011-04-15, 2013-04-15, someotherstatus
Smith, A2, 2015-04-03, null, transfer
Smith, B4, 2013-10-15, 2015-04-03, someotherstatus
Smith, B8, 2011-04-15, 2013-10-15, somestatus
我想带回的是以下内容。
Bob,A1,2015-04-03,null,转让当前房间 鲍勃,B5,2013-04-15,2015-04-03以前的房间 Smith,A2,2015-04-03,null,转让当前房间 Smith,B4,2013-10-15,2015-04-03上一个房间
如果这一点足够清楚,请告诉我。
我目前拥有的是
Select Name, room_number, Start_Date, End_Date, status
from TableX
where start_date = today
and status = transfer
这给了我所有人的房间。不知道如何获得以前的房间号码,因为转移之外的状态并不意味着什么。通用性是,如果结束日期是他们当前的房间
,则结束日期不为空由于
答案 0 :(得分:0)
CREATE VIEW RoomChange
AS
WITH CTE
AS
(
SELECT Name,
room_number,
[Start_Date],
[end_date],
ROW_NUMBER() OVER (PARTITION BY name ORDER BY [Start_date]) room_order
FROM TableX
)
SELECT A.name,
A.[Start_Date],
A.room_number,
B.[Start_Date] prev_room_start,
B.room_number AS prev_room
FROM CTE A
INNER JOIN CTE B
ON A.room_order = B.room_order + 1
AND A.Name = B.name
WHERE A.[end_date] IS NULL --only grab latest room
GO
SELECT *
FROM RoomChange
结果:
name Start_Date room_number prev_room_start prev_room
----- ---------- ----------- --------------- ---------
Bob 2015-04-03 A1 2013-04-15 B5
Smith 2015-04-03 A2 2013-10-15 B4