2
我有下列表,稱爲tbl_Rights
和tbl_Rights_history
,其中包含有關僱員權利和修改歷史記錄的 信息。SQL Server 2008 R2:將列拆分爲兩部分
表結構:
CREATE TABLE Tbl_Rights
(
Rights_ID int,
Rights_name varchar(10)
);
CREATE TABLE Tbl_Rights_history
(
EMPID int,
EMPName varchar(50),
Rights_ID int,
ModifiedDate datetime
);
插入數據:
INSERT INTO Tbl_Rights VALUES(1,'Guest')
INSERT INTO Tbl_Rights VALUES(2,'Admin')
INSERT INTO Tbl_Rights_history VALUES(1,'Sam',1,'2010-01-01 10:12:02.563')
INSERT INTO Tbl_Rights_history VALUES(1,'Sam',2,'2010-01-02 11:32:10.125')
INSERT INTO Tbl_Rights_history VALUES(1,'Sam',1,'2010-01-03 12:22:11.478')
INSERT INTO Tbl_Rights_history VALUES(2,'Mak',1,'2010-02-01 11:44:16.196')
INSERT INTO Tbl_Rights_history VALUES(2,'Mak',2,'2010-03-02 12:37:26.568')
預期輸出:
EMPName Old_Rights New_Rights ModifiedDate_1 ModifiedDate_2
----------------------------------------------------------------------------------
Sam Guest Admin 2010-01-01 10:12:02.563 2010-01-02 11:32:10.127
Sam Admin Guest 2010-01-02 11:32:10.127 2010-01-03 12:22:11.477
Mak Guest Admin 2010-02-01 11:44:16.197 2010-03-02 12:37:26.567
我嘗試:
;WITH CTE1 AS
(
SELECT t1.EMPID,
t1.EMPName,
t2.Rights_name,
t1.ModifiedDate,
DENSE_RANK() OVER(PARTITION BY t1.EMPID ORDER BY t1.ModifiedDate ASC) rn
FROM Tbl_Rights_history t1
LEFT JOIN Tbl_Rights t2
ON t1.Rights_ID = t2.Rights_ID
)
SELECT c.EMPName,
CASE WHEN rn = 1 THEN c.Rights_Name END Old_Rights,
CASE WHEN rn > 1 THEN c.Rights_Name END New_Rigths,
CASE WHEN rn = 1 THEN c.ModifiedDate END ModifiedDate_1,
CASE WHEN rn > 1 THEN c.ModifiedDate END ModifiedDate_2
FROM CTE1 c;
但是,得到意想不到的輸出:
EMPName Old_Rights New_Rigths ModifiedDate_1 ModifiedDate_2
-------------------------------------------------------------------------------
Sam Guest NULL 2010-01-01 10:12:02.563 NULL
Sam NULL Admin NULL 2010-01-02 11:32:10.127
Sam NULL Guest NULL 2010-01-03 12:22:11.477
Mak Guest NULL 2010-02-01 11:44:16.197 NULL
Mak NULL Admin NULL 2010-03-02 12:37:26.567
什麼是優雅的解決方案 –