DENSE_RANK() without duplication

后端 未结 4 972
一生所求
一生所求 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:41

    I think this is possible in pure SQL using some gaps and islands tricks, but the path of least resistance might be to use a session variable combined with LAG() to keep track of when your computed dense rank changes value. In the query below, I use @a to keep track of the change in the dense rank, and when it changes this variable is incremented by 1.

    DECLARE @a int
    SET @a = 1
    SELECT t.col1,
           t.col2,
           t.denserank,
           @a = CASE WHEN LAG(t.denserank, 1, 1) OVER (ORDER BY t.col1) = t.denserank
                     THEN @a
                     ELSE @a+1 END AS [whatiwant]
    FROM
    (
        SELECT col1, col2, DENSE_RANK() OVER (ORDER BY COL2) AS [denserank]
        FROM [table1]
    ) t
    ORDER BY t.col1
    

提交回复
热议问题