Home  >  Article  >  Database  >  SQL 关于row_number()over()

SQL 关于row_number()over()

WBOY
WBOYOriginal
2016-06-07 17:44:101180browse

SQL 关于row_number()over() 今天用到了row_number()over(),现在就以知识点的形式总结一下,以便于以后的回顾。 ------------------- 参考资料MSDN ------------------- 语法: ROW_NUMBER ( )OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_

SQL 关于row_number()over()

今天用到了row_number()over(),网站空间,现在就以知识点的形式总结一下,以便于以后的回顾。

-------------------参考资料MSDN-------------------

语法:

ROW_NUMBER ( ) OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )

通过语法可以看出 over里有两个参数, partition by 和 order by ,网站空间,其中partition by是可以不写的,但是order by是必须有的。可能对order by 比较熟悉(就是按什么排序),但 partition by是什么意思呢?partition  的中文解释是:n. 划分,分开;[数] 分割;隔墙;隔离物 vt. [数] 分割;分隔;区分。让我们再结合下面的参数说明和实例很容易就理解它的含义了。

 

参数:

返回值类型:

bigint(长整型)

以上是对row_number()over()的理论了解,现在开始用例子演示:

先建表(dbo.PeopleInfo):

.( (1,1) NOT NULL, (10) COLLATE Chinese_PRC_CI_AS NULL, (10) COLLATE Chinese_PRC_CI_AS NULL, (10) COLLATE Chinese_PRC_CI_AS NULL, (10) COLLATE Chinese_PRC_CI_AS NULL, )

向表中插入数据:

,Gender,numb,phone,fenshu) ,,,,80) ,Gender,numb,phone,fenshu) ,,,,90) ,Gender,numb,phone,fenshu) ,,,,56) ,Gender,numb,phone,fenshu) ,,,,60) ,Gender,numb,phone,fenshu) ,,,,80)

查询出所有插入的数据:

dbo.PeopleInfo

结果如图:



例子一:只用order by 不用 partition by 的sql语句如下:

,gender,fenshu, row_number() over(order by fenshu desc) as num from dbo.PeopleInfo

结果如图:

例子二:用order by 也用 partition by 的sql语句如下:

,gender,fenshu, row_number() over(partition by Gender order by fenshu desc) as num from dbo.PeopleInfo

结果如图:

比较例子一和例子二的结果图很容易就明白partition by的用处了,以例子二为例就是先用partition by把性别【Gender】分成两个区一个男一个女,香港虚拟主机,然后再用order by 把每个区里的分数【fenshu】从大到小排序。

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

练习题(用到了前面所讲的cte(with。。。as)知识点可以看看):

( ,gender,fenshu, row_number() over(partition by Gender order by fenshu desc) as num from dbo.PeopleInfo ) num = 1

结果如图:

 

 

 

 

 

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn