SQL OVER用法
- sql over的作用及用法
- RANK ( ) OVER ( [query_partition_clause] order_by_clause )
- DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause )
- 可实现按指定的字段分组排序,对于相同分组字段的结果集进行排序,
- 其中PARTITION BY 为分组字段,ORDERBY 指定排序字段
- over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。
- 其参数:over(partition by columnname1 orderby columnname2)
- 含义:按columname1指定的字段进行分组排序,或者说按字段columnname1的值进行分组排序。
- 例如:employees表中,有两个部门的记录:department_id =10和20
- select department_id,rank() over(partition by department_id orderby salary) from employees就是指在部门10中进行薪水的排名,在部门20中进行薪水排名。如果是partition by org_id,则是在整个公司内进行排名。
sql over的作用及用法 RANK ( ) OVER ( [query_partition_clause] order_by_clause ) DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause ) 可实现按指定的字段分组排序,对于相同分组字段的结果集进行排序, 其中PARTITION BY 为分组字段,ORDER BY 指定排序字段 over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。 其参数:over(partition by columnname1 order by columnname2) 含义:按columname1指定的字段进行分组排序,或者说按字段columnname1的值进行分组排序。 例如:employees表中,有两个部门的记录:department_id =10和20 select department_id,rank() over(partition by department_id order by salary) from employees就是指在部门10中进行薪水的排名,在部门20中进行薪水排名。如果是partition by org_id,则是在整个公司内进行排名。
--------------------------------------------------------------------------------------------
以上为示例1
- Select ID, Position + datediff(day, PDate, getdate()) as Position,PDate, Row_Number() over(orderby Position) as Sort
- From OverTest
Select ID, Position + datediff(day, PDate, getdate()) as Position,PDate, Row_Number() over(order by Position) as Sort From OverTest
--------------------------------------------------------------------------------------------
以上为示例2
- sql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY table1.BookingBranch, table1.RefNo) AS RowId, * From ("
- + sql.toString() + ") as Table1) as Table2 WHERE Table2.RowId BETWEEN " + startRow + " AND " + endRow;
sql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY table1.BookingBranch, table1.RefNo) AS RowId, * From (" + sql.toString() + ") as Table1) as Table2 WHERE Table2.RowId BETWEEN " + startRow + " AND " + endRow;
--------------------------------------------------------------------------------------------
以上为示例3