数据库技术之rank、dense_rank、ntile、row_number函数

CREATETABLEStudent

(

       StudentIDint,

     ClassIDint,

       Markint

 );
然后在表中插入数据

INSERTINTOStudent VALUES(1,1,90);

INSERTINTOStudent VALUES(2,1,84);

INSERTINTOStudent VALUES(3,1,80);

INSERTINTOStudent VALUES(5,1,90);

INSERTINTOStudent VALUES(6,1,76);

INSERTINTOStudent VALUES(7,1,89);

INSERTINTOStudent VALUES(11,2,90);

INSERTINTOStudent VALUES(12,2,82);

INSERTINTOStudent VALUES(13,2,80);

INSERTINTOStudent VALUES(14,2,80);

INSERTINTOStudent VALUES(15,2,90);

INSERTINTOStudent VALUES(16,2,75);

INSERT INTO Student VALUES(17,2,89);
------------------

rank函数:

SELECT*

    ,RANK()OVER(           --使用RANK函数进行排名

    PARTITIONBYClassID            --使用ClassID进行分组

    ORDERBYMarkDESC) AS [RANK] --使用Mark进行排序

FROMStudent

注:Partition by进行分组,返回一个分组中的多条记录

注:前2条数据相同的mark会根据数据生成序号

Dense_rank:

Select  *,dense_rank() over(Partition by ClassId order by mark desc) as [rank] from Student

注:生成的序号都是连续的

ntile函数:

select *,ntile(2) over(order by mark desc)as NewClass from Student

Row_number函数:

select *,row_number() over(partition by classId order by Mark desc) as orderId from student

猜你喜欢

转载自www.cnblogs.com/AChongi/p/10976606.html
今日推荐