TSQL - 从另一个表中的最大ID值更新

时间:2016-03-02 13:40:25

标签: tsql sql-update

我需要一些帮助来实现以下目标:

来源表:

tbl_ID  name    Row_id  change_time
1       test1   1             2016-01-01 09:00:00
1       test2   2             2016-01-01 10:00:00
50      test3   3             2016-02-01 09:00:00
50      test4   4             2016-02-01 11:00:00
66      test50  5             2016-03-01 11:00:00

目的地表:

tbl_ID  name    Row_id   RecordStatus
1       test1   1         Expired
1       test2   2         Expired ----need to update this to  'New Record'
50      test3   3         Expired
50      test4   4         Expired ---- need to update this to  'New Record'
66      test50  5         Expired ---- need to update this to  'New Record'        

我需要使用'新记录'更新目标表记录状态列。通过以下方式加入源表:

  • tbl_ID
  • Row_id列。

' change_time'每个ID都是MAX。

对代码的任何建议我将不胜感激。

1 个答案:

答案 0 :(得分:0)

这应该这样做:

示例数据:

CREATE TABLE #temp(tbl_ID      INT,
                name        VARCHAR(50),
                Row_id      INT,
                change_time DATETIME);

INSERT INTO #temp
VALUES
      (1, 'test1', 1, '2016-01-01 09:00:00'),
      (1, 'test2', 2, '2016-01-01 10:00:00'),
      (50, 'test3', 3, '2016-02-01 09:00:00'),
      (50, 'test4', 4, '2016-02-01 11:00:00'),
      (66, 'test50', 5, '2016-03-01 11:00:00');

CREATE TABLE #temp2(tbl_ID       INT,
                name         VARCHAR(50),
                Row_id       INT,
                RecordStatus VARCHAR(50));

INSERT INTO #temp2
VALUES
      (1, 'test1', 1, 'Expired'),
      (1, 'test2', 2, 'Expired'), ----need to update this to  'New Record'
      (50, 'test3', 3, 'Expired'),
      (50, 'test4', 4, 'Expired'), ---- need to update this to  'New Record'
      (66, 'test50', 5, 'Expired');  ---- need to update this to  'New Record' 

QUERY:

;WITH A
    AS (SELECT *,
             RANK() OVER(PARTITION BY tbl_ID ORDER BY change_time) AS Ranking
        FROM   #temp),
    B
    AS (SELECT A.*
        FROM   A
             INNER JOIN
                     (SELECT tbl_ID,
                            MAX(Ranking) Ranking
                      FROM   A
                      GROUP BY tbl_ID) AS B ON A.tbl_ID = B.tbl_ID
                                          AND A.Ranking = B.Ranking)
    UPDATE A
      SET  A.RecordStatus = 'New Record'
    FROM #temp2 AS A
        INNER JOIN B B ON A.tbl_ID = B.tbl_ID
                       AND A.Row_id = B.Row_id;

结果:

SELECT *
FROM   #temp2;

enter image description here