使用 CTE 可以帮助您。
DECLARE @Temp TABLE
(
ID INT,
current_dept NVARCHAR(100),
Dept_Start_Date DATETIME,
Name NVARCHAR(100)
)
INSERT INTO @Temp
(ID, current_dept, Dept_Start_Date, Name)
VALUES
(1, 'Sales', '2012-01-01', 'John Smith'),
(1, 'Marketing', '2010-01-01', 'John Smith'),
(1, 'Intern', '2008-01-01', 'John Smith'),
(2, 'IT', '2012-01-01', 'Sue Jones'),
(2, 'Sales', '2011-01-01', 'Sue Jones'),
(2, 'eBusiness', '2010-01-01', 'Sue Jones'),
(3, 'Warehouse', '2012-01-01', 'Bobby Ray'),
(3, 'Sales', '2009-01-01', 'Bobby Ray')
DECLARE @current_dept NVARCHAR(100) = 'Sales'
;WITH CurrentDeptCTE AS
(
SELECT ID, current_dept, Dept_Start_Date, Name, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Dept_Start_Date DESC) AS SEQUENCE
FROM @Temp
)
SELECT SalesDept.ID, DeptBefore.current_dept AS 'DeptBefore', DeptAfter.current_dept AS 'DeptAfter', CurrentDept.current_dept AS 'CurrentDept'
FROM
(
SELECT ID, SEQUENCE
FROM CurrentDeptCTE
WHERE current_dept = @current_dept
) SalesDept
LEFT JOIN CurrentDeptCTE AS DeptBefore ON SalesDept.ID = DeptBefore.ID AND SalesDept.SEQUENCE = DeptBefore.SEQUENCE - 1
LEFT JOIN CurrentDeptCTE AS DeptAfter ON SalesDept.ID = DeptAfter.ID AND SalesDept.SEQUENCE = DeptAfter.SEQUENCE + 1
LEFT JOIN
(
SELECT ID, current_dept
FROM CurrentDeptCTE
WHERE SEQUENCE = 1
) CurrentDept ON SalesDept.ID = CurrentDept.ID