DENSE_RANK() without duplication

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

    I would do it with a recursive cte like this:

    declare @Dept table (col1 integer, col2 integer)
    
    insert into @Dept values(1, 1),(2, 1),(3, 2),(4, 2),(5, 1),(6, 2),(7, 2),(8, 3)
    
    ;with a as (
    select col1, col2, 
    ROW_NUMBER() over (order by col1) as rn
    from @Dept),
    s as 
    (select col1, col2, rn, 1 as dr from a where rn=1
    union all
    select a.col1, a.col2, a.rn, case when a.col2=s.col2 then s.dr else s.dr+1 end as dr 
    from a inner join s on a.rn=s.rn+1)
    col1, col2, dr from s
    
    result:
    
    col1        col2        dr
    ----------- ----------- -----------
    1           1           1
    2           1           1
    3           2           2
    4           2           2
    5           1           3
    6           2           4
    7           2           4
    8           3           5
    

    The ROW_NUMBER is only required in case your col1 values are not sequential. If they are you can use the recursive cte straight away

提交回复
热议问题