SELECT only latest record of an ID from given rows

前端 未结 4 512
生来不讨喜
生来不讨喜 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:05

    This is typically referred to as the "greatest-n-per-group" problem. One way to solve this in SQL Server 2005 and higher is to use a CTE with a calculated ROW_NUMBER() based on the grouping of the id column, and sorting those by largest changeno first:

    ;WITH cte AS 
    (
      SELECT id, data, changeno,
        rn = ROW_NUMBER() OVER (PARTITION BY id ORDER BY changeno DESC)
      FROM dbo.Table1
    )
    SELECT id, data, changeno
      FROM cte
      WHERE rn = 1
      ORDER BY id;
    

提交回复
热议问题