创建一个引用其他列及其值的列?

时间:2019-12-09 16:52:38

标签: sql sql-server dynamic-sql data-munging

我正在尝试创建一个时间序列,以显示特定列在特定时间的值。我当前只能访问的表是记录所有更改,列的当前值,日期和已更改的列的名称的表。我想创建一个新列,该列跟踪更改之前该列的先前值。 “ Column_name”

中引用的更改中有63列以上

这是我目前拥有的

________________________________________________
Name |  date    |A  | B  |C  |NEW | Column_name|
bob  |  12302019|2  | 23 |153|2   | a          |
bob  |  12102019|2  | 23 |153|362 | a          |
bob  |  10242019|2  | 23 |153|7   | a          | 
john |  10062017|684| 452|1  |254 | c          |
john |  11052018|684| 452|1  |1   | c          |
________________________________________________

这就是我想要帮助创建的

_____________________________________________________
Name |  date    |A  | B  |C  |NEW | Column_name| Old |
bob  |  12302019|2  | 23 |153|2   | a          | 362 | 
bob  |  12102019|2  | 23 |153|362 | a          | 7   |
bob  |  10242019|2  | 23 |153|7   | a          |     | 
john |  10062017|684| 452|1  |254 | c          | 458 |
john |  11052018|684| 452|1  |1   | c          | 254 |
______________________________________________________

2 个答案:

答案 0 :(得分:0)

您似乎想要lag()

select t.*,
       lag(new) over (partition by name order by date) as old
from t;

答案 1 :(得分:0)

您已经有了答案,它是LAG():

CREATE TABLE #test
(
    UserName VARCHAR(20),
    TheDate DATE,
    A INT,
    B INT,
    C INT,
    ColumnName NVARCHAR(128),
    New INT
);

INSERT INTO #test(UserName, TheDate, A, B, C, ColumnName, New)
VALUES 
('bob', '20191230', 2, 23, 153, 'a', 2),
('bob', '20191210', 2, 23, 153, 'a', 362),
('bob', '20191024', 2, 23, 153, 'a', 7),
('john', '20171006', 684, 452, 1, 'c', 458),
('john', '20181105', 684, 452, 1, 'c', 254);

SELECT *, LAG(New) OVER(PARTITION BY A, B, C, ColumnName ORDER BY TheDate) AS Old
FROM #test
ORDER BY A, B, C, TheDate;