DENSE_RANK() without duplication

后端 未结 4 955
一生所求
一生所求 2021-01-13 03:58

Here\'s what my data looks like:

| col1 | col2 | denserank | whatiwant |
|------|------|-----------|-----------|
| 1    | 1    | 1         | 1         |
| 2          


        
4条回答
  •  日久生厌
    2021-01-13 04:34

    Here is one way using SUM OVER(Order by) window aggregate function

    SELECT col1,Col2,
           Sum(CASE WHEN a.prev_val = a.col2 THEN 0 ELSE 1 END) OVER(ORDER BY col1) AS whatiwant 
    FROM   (SELECT col1,
                   col2,
                   Lag(col2, 1)OVER(ORDER BY col1) AS prev_val
            FROM   Yourtable) a
    ORDER  BY col1; 
    

    How it works:

    LAG window function is used to find the previous col2 for each row ordered by col1

    SUM OVER(Order by) will increment the number only when previous col2 is not equal to current col2

提交回复
热议问题