How to Reset DENSE_RANK for new group

Papillon28 86 Reputation points
2020-08-18T13:59:35.78+00:00

Hi All,

How to reset DENSE_RANK for new set

DDL and sample data population, start
drop table if exists #t
select * into #t
from
(select 1 as ID, 'a1' as address,'p1' as phone) p

insert into #t
select 1, 'a1', 'p2'
union
select 1,'a2','p3'
union
select 2,'a4','p4'
union
select 2,'a4','p5'
union
select 3,'a5','p6'
-- DDL and sample data population, end

select ID,Address, Phone, DENSE_RANK() OVER(ORDER BY ID, Address) as Add_No_Rank
from #t

Output need (ID and Address column are in Group)
1 a1 p1 1
1 a1 p2 1
1 a2 p3 2
2 a4 p4 1
2 a4 p5 1
3 a5 p6 1

SQL SERVER Version
2016

T.I.A

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,589 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2020-08-18T23:11:40.333+00:00
    select ID,Address, Phone
    , DENSE_RANK() OVER(Partition by ID  ORDER BY Address) as Add_No_Rank
    from #t
    /*
    ID  Address Phone   Add_No_Rank
    1   a1  p1  1
    1   a1  p2  1
    1   a2  p3  2
    2   a4  p4  1
    2   a4  p5  1
    3   a5  p6  1
    
    */
    
    0 comments No comments