大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说sqlserver row_number_row_number() over order by,希望您对编程的造诣更进一步.
语法:ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
简单的说ROW_NUMBER()从1开始,为每一条分组记录返回一个数字,这里的ROW_NUMBER() OVER (ORDER BY CYLH DESC) 是先把xlh列降序,再为降序以后的每条CYLH记录返回一个序号。
示例: CYLH ROW_MUM
1900 1
1600 2
1185 3
780 4
分析:ROW_NUMBER() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组,在分组内部根据 COL2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)
也可这样使用:ROW_NUMBER() OVER (ORDER BY COL2)
例子:
建立测试表,并插入测试数据
CREATE TABLE TEST_ROW_NUMBER_01( CMZH varchar(10) not null, CYLH varchar(10) null, MJE money null, );
INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES (2106000011,20281997,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000010,20281996,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000008,20281995,0.00) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000006,20281994,9.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000004,20281993,5.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000001,20281992,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000002,20281992,10.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000007,20217280,0.00) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000009,20172458,5.50) INSERT INTO TEST_ROW_NUMBER_01(CMZH,CYLH,MJE) VALUES(2106000005,20121813,0.00)
执行脚本自动生成行号并按CYLH进行排序(滑动查看代码)
SELECT ROW_NUMBER()OVER(ORDER BY CYLH DESC) AS ROWNUM,* FROM TEST_ROW_NUMBER_01
结果如下:
注意:在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/5654.html