码迷,mamicode.com
首页 > 数据库 > 详细

SQL Server 排名函数实现

时间:2015-04-08 17:56:31      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

在SQL Server 中有四大排名函数分别是:

1、row_number()

2、ntile()

3、rank()

4、dense_rank()

-------------------------------------------------------------------------

为了方便演示我们先建立相关的表

create table t(ID int ,Name varchar(32));
go

insert into t(ID,Name) values(1,‘A‘),(2,‘A‘),(3,‘B‘),(4,‘C‘),(5,‘C‘),(6,‘D‘);
go

1、

  row_number();

    select ID,Name,ROW_NUMBER() over(order by Name) as rowNumber

    from t;

    go

    技术分享

    select ID,Name,(select count(*) from t as b where b.ID<=a.ID) as rowNumber
    from t as a;
    go

    技术分享

2、

  ntile()

    select ID,Name,ntile(3) over(order by ID) nitleNumber from t;

    go

    技术分享

    declare @count as int =6;

    declare @groupsize as int =3;
    declare @tilesize as int =@count/@groupsize;

    select ID,Name,((select count(*)+1 from t as b where a.ID>=b.ID)/@tilesize) ntileNumber
    from t as a;
    go

    技术分享

3、

  rank()

    select ID,Name,rank() over(order by Name)
    from t;
    go

    技术分享

    select ID,Name,(select count(*)+1 from t as b where b.Name <a.Name)

    from t as a;

    技术分享go

    

 

 

    

 

SQL Server 排名函数实现

标签:

原文地址:http://www.cnblogs.com/JiangLe/p/4403067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!