T-SQL:开窗函数的常见应用

为每条数据显示聚合信息(聚合函数()over())

查询每个工资小于5000元的员工信息(城市以及年龄),并且在每行中都显示所有工资小于5000元的员工个数

select City,Age,count(*)over()
from Person
where Salary<5000;
City Age
Beijing 20 5
Londonu 21 5
London 23 5
Beijing 22 5
NewYork 24 5

为每条数据提供分组的聚合函数结果(聚合函数()over(partion by 字段)as 别名)

查询每一个人员的信息以及所属城市的人员数

select Name,City,Age,Salary,count(*)over(parttion byCity)
from Person;
Name City Age
Tom Beijing 20 4
Jim Beijing 21 4
Merry Beijing 23 4
Bill Beijing 22 4
Swing NewYork 24 3
Guo NewYork 24 3
John NewYork 20 3
Jerry London 24 2
Danny London 25 2

与排名函数一起使用(row number()over(order by 字段)as 别名)

row number()函数用于计算一行在结果集中的行号。
在分页查询中,若根据id来限制每页的行数,每页数据经过一系列修改后,id可能不再连续,若再根据id来限制每页行数,显示的结果可能就会和实际预想的不同。
则可添加一列,来代表行数,他是连续的。

select
    num
    , stuId
    , stuName
    , stuSex
    , stuBirthdate
    , stuStudydate
    , stuAddress
    , stuEmail
    , stuPhone
    , stuIsDel
    , stuInputtime
    , classId
from (
    select 
        row_number() over(order by stuid) as num
        , stuId
        , stuName
        , stuSex
        , stuBirthdate
        , stuStudydate
        , stuAddress
        , stuEmail
        , stuPhone
        , stuIsDel
        , stuInputtime
        , classId
    from 
        TestDataBase..Student
    where 
        stuIsDel = 0) as t
where 
    t.num between (10-1)*9+1 and 9*10;

每页m条,第n页
每一页的第一条就是上一页加一条,m*(n-1)+1

你可能感兴趣的:(T-SQL:开窗函数的常见应用)