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

前端 未结 4 1890
南方客
南方客 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:22

    If your RDBMS supports Window Aggregate functions and/or LEAD() and LAG() functions you can leverage them to accomplish what you are trying to report. The following SQL will help get you started down the right path:

    SELECT id
         , Col AS CurCol
         , MAX(Col)
           OVER(ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS PrevCol
         , MIN(COL)
           OVER(ORDER BY id ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING) AS NextCol
    FROM MyTable
    

    From there you can put that SQL in a derived table with some CASE logic that if the NextCol or PrevCol is the same as CurCol then set CurCol = NULL. Then you can collapse eliminate all the id records CurCol IS NULL.

    If you don't have the ability to use window aggregates or LEAD/LAG functions your task is a little more complex.

    Hope this helps.

提交回复
热议问题