sql关键字——with 子查询,row_number()排名函数,lag()函数用法举例

题目:
查询所有选修"英语"的学生成绩与前一名的分数差距,按照成绩降序排序。

针对以上需求,有两种做法

1.使用lag函数

lag()函数,取当前行的上一列,用法是lag(列,往上取的行数,填充值),如lag(score, 1, 0)

表示取score这一列当前行的上一行作为新的一行,若超出窗口范围,则给值为0

lag(score,1,0) over(order by score desc) lag_score
1.取上一行的分数
select
    name,
    subject,
    score,
    lag(score,1,0) over(order by score desc) lag_score
from default.score
where subject = '英语'
2.将两个分数相减

考虑到第一名同学没有上一行数据,给予0

if(lag_score - score > 0, lag_score - score, 0) score_diff
3.最终SQL
select
    name,
    score,
    lag_score,
    if(lag_score - score > 0, lag_score - score, 0) score_diff
from
(
    select
        name,
        subject,
        score,
        lag(score,1,0) over(order by score desc) lag_score
    from default.score
    where subject = '英语'
)t1

2.使用排名函数row_number来解决

思路:
问题:排名总数会减少?

rank()函数在进行排名时,值相同,总数排名会跳过,这样在进行关联时,等号左右两边关联不上,数据减少。

所以这里使用row_number()进行排名,分数相同,排名顺序递增。

1.取当前学生的分数排名
    使用with表达式,很好的提高了SQL复用性

     这里将排名存储在虚表中,避免二次查询。

with RankScore as (
    select
    name,
    subject,
    score,
    -- 使用rank()导致排名减少,造成关联不上
    row_number()  over(partition by subject order by score desc) rk
from default.score
where subject = '英语'
)
2. 关联该同学的排名与他的上一名排名, 将当前排名 = 上一行排名 + 1, 差值为1,即为本行与上一行
select

from RankScore a
    -- 当前名与上一名学生的差距。
join RankScore b on a.rk = b.rk + 1
order by a.score desc
3. 使用当前行分数-上一行分数,得到分差
select
    a.name,
    a.subject,
    a.score,
    a.score - b.score as score_diff
from RankScore a
    -- 当前名与上一名学生的差距。
join RankScore b on a.rk = b.rk + 1
order by a.score desc
4.最终SQL
with RankScore as (
    select
    name,
    subject,
    score,
    -- 使用rank()导致排名减少,造成关联不上
    row_number()  over(partition by subject order by score desc) rk
from default.score
where subject = '英语'
)

select
    a.name,
    a.subject,
    a.score,
    a.score - b.score as score_diff
from RankScore a
    -- 当前名与上一名学生的差距。
join RankScore b on a.rk = b.rk + 1
order by a.score desc

通过这道题,我们学习了排名函数、虚拟表的使用。

  • 21
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值