select *,ROW_NUMBER() over(partition by deviceID order by RecordDate deschtml
row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根據COL1分組,在分組內部根據 COL2排序,而此函數計算的值就表示每組內部排序後的順序編號(組內連續的惟一的)函數
實例:htm
初始化數據blog
create table employee (empid int ,deptid int ,salary decimal(10,2))排序
insert into employee values(1,10,5500.00)ci
insert into employee values(2,10,4500.00)get
insert into employee values(3,20,1900.00)it
insert into employee values(4,20,4800.00)io
insert into employee values(5,40,6500.00)table
insert into employee values(6,40,14500.00)
insert into employee values(7,40,44500.00)
insert into employee values(8,50,6500.00)
insert into employee values(9,50,7500.00)
數據顯示爲
empid deptid salary ----------- ----------- ---------------------------------------
1 10 5500.00
2 10 4500.00
3 20 1900.00
4 20 4800.00
5 40 6500.00
6 40 14500.00
7 40 44500.00
8 50 6500.00
9 50 7500.00
需求:根據部門分組,顯示每一個部門的工資等級
預期結果:
empid deptid salary rank ----------- ----------- --------------------------------------- --------------------
1 10 5500.00 1
2 10 4500.00 2
4 20 4800.00 1
3 20 1900.00 2
7 40 44500.00 1
6 40 14500.00 2
5 40 6500.00 3
9 50 7500.00 1
8 50 6500.00 2
SQL腳本:
SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee
轉自:http://www.cnblogs.com/digjim/archive/2006/09/20/509344.html