2012-02-14 61 views
0

我有兩個表EmployeeEmployeeLog(與除LogCreatedDate同一列)需要T-SQL的幫助2005

列是這樣的:

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

感謝

+0

我通過LogCreatedDate DESC有TOP 2創紀錄的訂單,現在怎麼這兩行比較,並安排爲每在圖片 – Sukhjeevan 2012-02-14 09:25:37

回答

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 
+0

顯示錶格感謝Rubens.Thanks很多。它真的幫助我。它真棒,它完全按照我的需要。 +1爲您的迴應。 – Sukhjeevan 2012-02-15 06:14:59

+0

我還有一件事要做的是,現在我想過濾出這個結果集,以便它應該只顯示那些已經改變列值的記錄,即消除具有相同的前一個和當前值的記錄 – Sukhjeevan 2012-02-15 06:36:05

+0

請參閱我的結果集2問題作爲參考。現在它應該過濾掉rowno 1&3 NOT 2。 – Sukhjeevan 2012-02-15 06:40:42