旧的& SQL中的新值

时间:2014-12-01 07:35:59

标签: sql sql-server sql-server-2008 tsql

我有一张如下表格。

 EmpName   Sta_CD   Comments
 AAAAAA     1        One
 AAAAAA     2        two
 AAAAAA     2        two_Updated
 AAAAAA     2        two_UpdatedAgain
 AAAAAA     3        Three
 AAAAAA     4        Four

我正在尝试跟踪员工的Sta_CD的新旧值,就像下面一样。

 EmpName Old_Sta_CD   Sta_CD   Comments
 AAAAAA      Null        1        One
 AAAAAA       1          2        two
 AAAAAA       2          2        two_Updated
 AAAAAA       2          2        two_UpdatedAgain
 AAAAAA       2          3        Three
 AAAAAA       3          4        Four

可以AnyOne建议我如何获得此输出吗?

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()功能执行此操作,例如:

WITH Ranked
AS
(
  SELECT *,
    ROW_NUMBER() OVER(ORDER BY Sta_CD) AS RN
  FROM table1
)
SELECT 
  old.EmpName,
  new.Sta_CD AS Old_Sta_CD,
  old.Sta_CD,
  old.Comments
FROM Ranked AS old
LEFT JOIN Ranked AS new ON old.rn - 1 = new.rn;

这会给你:

| EMPNAME | OLD_STA_CD | STA_CD |         COMMENTS |
|---------|------------|--------|------------------|
|  AAAAAA |     (null) |      1 |              One |
|  AAAAAA |          1 |      2 |              two |
|  AAAAAA |          2 |      2 |      two_Updated |
|  AAAAAA |          2 |      2 | two_UpdatedAgain |
|  AAAAAA |          2 |      3 |            Three |
|  AAAAAA |          3 |      4 |             Four |

答案 1 :(得分:2)

如果您使用SQL SERVER 2012+

,请尝试此操作

使用 LAG 功能获取上一行

SELECT EmpName,
       Lag(sta_cd)
         OVER(
           partition BY empname
           ORDER BY Sta_CD)old_Sta_CD,
       Sta_CD,
       Comments
FROM   <tablename>

<强> SQL FIDDLE DEMO