T-SQL 当前和以前的状态
T-SQL Current and Previous Status
我有一个数据库,我想从中获取当前房间号和以前的房间号。
数据是这样的。
TableX
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, 调入当前房间
Bob, B5, 2013-04-15, 2015-04-03 上一个房间
Smith, A2, 2015-04-03, null, 转让 Current Room
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
这给了我所有的人房间。不确定如何获得以前的房间号,因为转移之外的状态没有任何意义。共同点是,如果是他们当前的房间,结束日期不为空
谢谢
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
我有一个数据库,我想从中获取当前房间号和以前的房间号。
数据是这样的。 TableX
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, 调入当前房间 Bob, B5, 2013-04-15, 2015-04-03 上一个房间 Smith, A2, 2015-04-03, null, 转让 Current Room 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
这给了我所有的人房间。不确定如何获得以前的房间号,因为转移之外的状态没有任何意义。共同点是,如果是他们当前的房间,结束日期不为空
谢谢
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