Turn: SqlServer four sorts: ROW_NUMBER()/RANK()/DENSE_RANK()/ntile() over()

The original text is reproduced from: http://blog.csdn.net/a5685263/article/details/52187070

 

The following is the reproduced content:

First, let's create some test data.

if OBJECT_ID('Tempdb.dbo.#Tmp') is not null
    drop table #Tmp
create table #Tmp
(
name nvarchar(10)
)

insert into #Tmp
select N'Zhang San'
union
select N'Li Si'
union
select N'Wang Wu'
union
select N'Zhao Liu'
union
select N'Zhu Qi'
union
select N'Wang Ba'
union all
select N'Zhang San'

PS: Union all is used for the last union, because we have one more line of "Zhang San".

 

一、ROW_NUMBER() over(partition by columnname order by columnname)

select ROW_NUMBER()over(order by name) as num,* from #Tmp

You can get the result set sorted by name.

There is also a usage of ROW_NUMBER() over() to group and sort a column.

In the following results, you can see that Zhang San has two sorts, 1 and 2, while the other names are only sorted by 1.

select ROW_NUMBER()over(partition by name order by name) as num,* from #Tmp

result:

 

2. RANK()over(order by columnname) :
As you can see from the result set below, the result set is missing the number of 5, but has two numbers of 4, and then jumps directly to number 6.

select RANK()over(order by name),* from #Tmp

Result:

  
3. DENSE_RANK()over(order by columnname) :

select DENSE_RANK()over(order by name),* from #Tmp

After executing Sql, it is found that the following result set has 2 rows with number 4, followed by the row with number 5.

The DENSE_RANK() function is similar to the RANK() function.
No matter how many groups the RANK() function is divided into, the final number must be the same as the number of rows.
The final number of the DENSE_RANK() function is related to the number of groups.

 

四、NTILE()OVER(ORDER BY COLUMNNAME)

select NTILE(2)over(order by name),* from #Tmp
select NTILE(3)over(order by name),* from #Tmp

The number after NTILE is to divide the results obtained by the query into several groups.
It is divided into 2 and 3 groups as shown in the figure below.
If there are remaining rows after the number of rows is evenly divided, then the rows are divided into the first groups.
For example, our result has 7 rows and should be divided into 3 groups.
Then the first set of 3 rows, the second set of 2 rows, and the third set of 2 rows.
If our result has 14 rows, it is divided into 3 groups equally.
Then the first set of 5 rows, the second set of 5 rows, and the third set of 4 rows.
So on and so forth.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326119724&siteId=291194637