在Sql Server 2005中需要T-SQL帮助

时间:2012-02-14 09:12:16

标签: asp.net sql-server-2005 tsql

我有两个表EmployeeEmployeeLog(除LogCreatedDate之外的列相同)

列是这样的:

EmployeeID, EmployeeName, LastModifiedBy, ModifiedDate,
ColumnA, ColumnB, ColumnC bla-bla-bla

我需要T-SQL,它给出了输出,如下表所示。

ResultSet 1:

enter image description here

在每个Employee表更新中,我在EmployeeLog表中插入一个包含当前值的新行。

EmployeeLog表包含每个EmployeeID的多行,因此我需要修改的列中的先前值和当前值。

所以我的第一步是按LogCreatedDate DESC获取TOP 2记录顺序。现在我应该如何获得输出,如表所示?

ResultSet 2: enter image description here

由于

1 个答案:

答案 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