Only select first row of repeating value in a column in SQL

前端 未结 4 1888
南方客
南方客 2021-02-08 10:07

I have table that has a column that may have same values in a burst. Like this:

+----+---------+
| id |   Col1  | 
+----+---------+
| 1  | 6050000 |
+----+----         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-08 10:16

    Since id is always sequential, with no gaps or repetitions, as per your comment, you could use the following method:

    SELECT t1.*
    FROM atable t1
      LEFT JOIN atable t2 ON t1.id = t2.id + 1 AND t1.Col1 = t2.Col1
    WHERE t2.id IS NULL
    

    The table is (outer-)joined to itself on the condition that the left side's id is one greater than the right side's and their Col1 values are identical. In other words, the condition is ‘the previous row contains the same Col1 value as the current row’. If there's no match on the right, then the current record should be selected.


    UPDATE

    To account for non-sequential ids (which, however, are assumed to be unique and defining the order of changes of Col1), you could also try the following query:

    SELECT t1.*
    FROM atable t1
      LEFT JOIN atable t2 ON t1.id > t2.id
      LEFT JOIN atable t3 ON t1.id > t3.id AND t3.id > t2.id
    WHERE t3.id IS NULL
      AND (t2.id IS NULL OR t2.Col1 <> t1.Col1)
    

    The third self-join is there to ensure that the second one yields the row directly preceding that of t1. That is, if there's no match for t3, then either t2 contains the preceding row or it's got no match either, the latter meaning that t1's current row is the top one.

提交回复
热议问题