Continuing my series on how same things can be done differently in SQL Server and MySQL, in this post, we will see how to implement Dense Rank in SQL Server vs MySQL.
Generating a dense_rank is a common requirement when showing resultsets. In SQL Server, starting from version 2005, we can make use of the dense_rank() function. Dense_rank() will generate the serial number for each set of values and keep the same number if the value is duplicated
Consider the following set of data
insert into test
select 'Suresh' union all
select 'Ramesh' union all
select 'Kant' union all
select 'Jerald' union all
select 'Clara' union all
select 'Ramesh' union all
select 'Kant' union all
select 'Jerald' union all
select 'John'
SQL Server
Using the dense_rank() function, we can generate a serial number and reset for each name
MySQL
Using a variable, we can generate the serial number, and use another variable that keeps same value for duplicates
set @sno:=0;
set @names:='';
select @sno:=case when @names=names then @sno else @sno+1 end as sno,@names:=names as names from test
order by names;
In the above example, variable @sno gets incremented by 1 for each set of values thus keeping the same value for duplicates.
3 comments:
In MySQL, what if I want result like this instead:
sno name
1 Clara
1 Jerald
2 Jerald
1 John
1 Kant
2 Kant
Thank you very much Madhivanan. This helped me with a ranking problem i was struggling with tonight. I truly appreciate people like yourself who take the time to share experience to help others.
Thank you sir!
You helped me a lot too.
Post a Comment