SELECT only latest record of an ID from given rows

前端 未结 4 409
生来不讨喜
生来不讨喜 2021-01-26 01:58

I have this table shown below...How do I select only the latest data of the id based on changeno?

+----+--------------+------------+--------+
| id |  data   | ch         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 02:13

    for other alternatives :

    DECLARE @Table1 TABLE
    (
     id INT, data VARCHAR(5), changeno INT
    );
    
    INSERT INTO @Table1
    SELECT 1,'Yes',1
    UNION ALL
    SELECT 2,'Yes',2
    UNION ALL
    SELECT 2,'Maybe',3
    UNION ALL
    SELECT 3,'Yes',4
    UNION ALL
    SELECT 3,'Yes',5
    UNION ALL
    SELECT 3,'No',6
    UNION ALL
    SELECT 4,'No',7
    UNION ALL
    SELECT 5,'Maybe',8
    UNION ALL
    SELECT 5,'Yes',9
    
    SELECT Y.id, Y.data, Y.changeno
    FROM @Table1 Y
    INNER JOIN (
        SELECT id, changeno = MAX(changeno) 
        FROM @Table1 
        GROUP BY id
    ) X ON X.id = Y.id 
    WHERE X.changeno = Y.changeno
    ORDER BY Y.id
    

提交回复
热议问题