选择SQL中的最新更改

时间:2016-07-19 17:28:29

标签: sql-server-2008

我有一个由四列组成的表:

TimeStamp | Leg1 | Leg2 | Leg3

我需要选择最近更改为最后一条腿的腿。

1 个答案:

答案 0 :(得分:0)

假设每个时间戳只会改变一个腿值,这将为您提供上次更改的时间,更改的腿数,新值的值以及之前的值。

以下链接可在行动http://rextester.com/ZZHB91131

中查看

代码在这里:

IF OBJECT_ID('tempdb..#thisTest') IS NOT NULL DROP TABLE #thisTest

CREATE TABLE #thisTest(
DateTimeStamp datetime,
Leg1 int,
Leg2 int,
Leg3 int)

INSERT INTO #thisTest (DateTimeStamp,Leg1,Leg2,Leg3) VALUES
('7/1/2016',1,1,1),
('7/2/2016',2,1,1),
('7/3/2016',2,2,1),
('7/4/2016',2,2,2),
('7/5/2016',2,2,3),
('7/6/2016',2,3,3),
('7/7/2016',3,3,3),
('7/8/2016',3,4,4),
('7/9/2016',4,3,4),
('7/10/2016',4,3,5),
('7/11/2016',4,4,5)

SELECT * FROM #thisTest

SELECT TOP 1
    DateTimeStamp as TimeOfLastChange,
    CASE 
        WHEN LEAD(Leg1) OVER(ORDER BY DateTimeStamp DESC) <> Leg1 THEN 'Leg1'
        WHEN LEAD(Leg2) OVER(ORDER BY DateTimeStamp DESC) <> Leg2 THEN 'Leg2'
        WHEN LEAD(Leg3) OVER(ORDER BY DateTimeStamp DESC) <> Leg3 THEN 'Leg3'
    END AS LegThatWasLastChanged,
    CASE 
        WHEN LEAD(Leg1) OVER(ORDER BY DateTimeStamp DESC) <> Leg1 THEN LEAD(Leg1) OVER(ORDER BY DateTimeStamp DESC)
        WHEN LEAD(Leg2) OVER(ORDER BY DateTimeStamp DESC) <> Leg2 THEN LEAD(Leg2) OVER(ORDER BY DateTimeStamp DESC)
        WHEN LEAD(Leg3) OVER(ORDER BY DateTimeStamp DESC) <> Leg3 THEN LEAD(Leg3) OVER(ORDER BY DateTimeStamp DESC)
    END AS PreviousLegValue,
    CASE 
        WHEN LEAD(Leg1) OVER(ORDER BY DateTimeStamp DESC) <> Leg1 THEN Leg1
        WHEN LEAD(Leg2) OVER(ORDER BY DateTimeStamp DESC) <> Leg2 THEN Leg2
        WHEN LEAD(Leg3) OVER(ORDER BY DateTimeStamp DESC) <> Leg3 THEN Leg3
    END AS LastLegValue
FROM
    #thisTest
ORDER BY
    DateTimeStamp DESC