I have the following tables called tbl_Rights and tbl_Rights_history which contains the
information about the employees rights and modification history.
Tables Structure:
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 data:
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')
Expected Output:
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
My attempt:
;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;
But getting unexpected output:
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