从历史记录表中获取最近更改的值

时间:2015-04-07 03:28:28

标签: sql sql-server tsql

我有一个包含以下值的历史记录表

CREATE TABLE History (SnapShotDate DATETIME, UID VARCHAR(10), DUEDATE DATETIME)

INSERT INTO History VALUES ('03-23-2015','PT-01','2015-04-22')
INSERT INTO History VALUES  ('03-30-2015','PT-01','2015-04-20')
INSERT INTO History VALUES  ('04-06-2015','PT-01','2015-06-30')

INSERT INTO History VALUES  ('03-23-2015','PT-02','2015-04-22')
INSERT INTO History VALUES  ('03-30-2015','PT-02','2015-04-22')
INSERT INTO History VALUES  ('04-06-2015','PT-02','2015-04-22')

INSERT INTO History VALUES  ('03-23-2015','PT-03','2015-04-18')
INSERT INTO History VALUES  ('03-30-2015','PT-03','2015-04-22')
INSERT INTO History VALUES  ('04-06-2015','PT-03','2015-04-22')

我需要以下格式的输出。我需要任何给定UID的最新更改值。请帮助我获得以下结果

输出

 UID    PreviousDueDate  CurrentDueDate
----------------------------------------
 PT-01     2015-04-20      2015-06-30
 PT-02     2015-04-22      2015-04-22
 PT-03     2015-04-18      2015-04-22

由于

5 个答案:

答案 0 :(得分:0)

您可以尝试使用此SQL:

select UID,date_format(min(DUEDATE), '%Y-%m-%d') as PreviousDueDate,date_format(max(DUEDATE), '%Y-%m-%d') as CurrentDueDate from History group by UID;

答案 1 :(得分:0)

SELECT UID, 
(SELECT DUEDATE FROM  History WHERE SnapShotDate=(SELECT MIN(SnapShotDate) FROM  History h2 WHERE h2.UID=h1.UID) )AS PreviousDueDate
(SELECT DUEDATE FROM  History WHERE SnapShotDate=(SELECT MAX(SnapShotDate) FROM  History WHERE h2.UID=h1.UID) )AS CurrentDueDate
FROM History h1
GROUP BY UID

答案 2 :(得分:0)

你应该在sql server中使用Convert函数。

SELECT A.UID
,CONVERT(varchar(10),B.DUEDATE, 20) as PreviousDueDate
,CONVERT(varchar(10),A.DUEDATE, 20) as CurrentDueDate
FROM
(
    SELECT *,row_number() OVER( PARTITION BY UID ORDER BY SnapShotDate DESC) AS ROWID
    FROM History
)A
LEFT JOIN
(
    SELECT *,row_number() OVER( PARTITION BY UID ORDER BY SnapShotDate DESC) AS ROWID
    FROM History
)B ON A.UID=B.UID AND B.ROWID=2
WHERE A.ROWID=1
GROUP BY A.UID,A.DUEDATE,B.DUEDATE

输出:

UID     PreviousDueDate CurrentDueDate
PT-01   2015-04-20      2015-06-30
PT-02   2015-04-22      2015-04-22
PT-03   2015-04-22      2015-04-22
PT-04   2015-04-22      2015-04-18

答案 3 :(得分:0)

我之前从未使用过LAG功能,但看起来非常简单!!!

; WITH CTE AS (
  SELECT UID, 
    LAG(DUEDATE,1,NULL) OVER (PARTITION BY UID ORDER BY SnapShotDate ASC) AS PreviousDueDate,
    DUEDATE AS CurrentDueDate,
    ROW_NUMBER() OVER (PARTITION BY UID ORDER BY SnapShotDate DESC) AS RowNumber
  FROM History
)
SELECT UID, PreviousDueDate, CurrentDueDate
FROM CTE
WHERE ROWNUMBER = 1

这是fiddle

答案 4 :(得分:0)

SELECT UID, 
(SELECT MIN(DUEDATE) FROM  History HS WHERE  HS.UID =  H.UID  GROUP BY  UID )AS PreviousDueDate,
(SELECT Max(DUEDATE) FROM  History HS WHERE  HS.UID =  H.UID GROUP BY  UID )AS CurrentDueDate
FROM History  H
GROUP BY UID