我有两个表Employee
和EmployeeLog
(除LogCreatedDate
之外的列相同)
列是这样的:
EmployeeID, EmployeeName, LastModifiedBy, ModifiedDate,
ColumnA, ColumnB, ColumnC bla-bla-bla
我需要T-SQL,它给出了输出,如下表所示。
ResultSet 1:
在每个Employee
表更新中,我在EmployeeLog
表中插入一个包含当前值的新行。
EmployeeLog
表包含每个EmployeeID
的多行,因此我需要修改的列中的先前值和当前值。
所以我的第一步是按LogCreatedDate DESC
获取TOP 2记录顺序。现在我应该如何获得输出,如表所示?
ResultSet 2:
由于
答案 0 :(得分:1)
试试这个:
DECLARE @EmployeeLog TABLE
(
EmployeeID int,
EmployeeName varchar(50),
LastModifiedBy varchar(50),
ModifiedDate datetime,
ColumnA varchar(50),
ColumnB varchar(50),
ColumnC varchar(50),
LogCreatedDate datetime
)
INSERT INTO @EmployeeLog VALUES (1, 'A', 'A', '2012-02-07', 'A', 'B', 'C', '2012-02-07')
INSERT INTO @EmployeeLog VALUES (1, 'B', 'B', '2012-02-06', 'AA', 'BB', 'CC', '2012-02-06')
;
WITH Basics AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY LogCreatedDate DESC) as Entry
FROM @EmployeeLog
), PivotTable AS
(
SELECT EmployeeID,
LastModifiedBy,
ModifiedDate,
'ColumnA' ColumnName,
ColumnA ColumnValue,
LogCreatedDate,
Entry
FROM Basics
UNION ALL
SELECT EmployeeID,
LastModifiedBy,
ModifiedDate,
'ColumnB' ColumnName,
ColumnB ColumnValue,
LogCreatedDate,
Entry
FROM Basics
UNION ALL
SELECT EmployeeID,
LastModifiedBy,
ModifiedDate,
'ColumnC' ColumnName,
ColumnC ColumnValue,
LogCreatedDate,
Entry
FROM Basics
)
SELECT [Current].LastModifiedBy, [Current].ModifiedDate,
Previous.EmployeeID, Previous.ColumnName,
Previous.ColumnValue [Previous Value],
[Current].ColumnValue [Current Value]
FROM PivotTable Previous
JOIN PivotTable [Current]
ON Previous.EmployeeID = [Current].EmployeeID AND
Previous.ColumnName = [Current].ColumnName AND
Previous.Entry = [Current].Entry + 1