SQL窗口函数

一张图小结窗口函数:

来自牛客网的原理解释

窗口函数

row_number() over partition by

函数的含义为先分组再排序, row_number() over (partition by col1 order by col2),

表示根据col1分组,在分组内部根据col2排序,为了更好的理解,我们来看个例 子

代码:

Select device_id, university,gpa,
row_number() over (partition by university order by gpa desc) as
rank. - -desc代表降序排列
From user_profile

上述代码含义为在每个学校的内部根据gpa进行一次排名,获得每个学生在学校的名次数据,desc代表是按照从大到小降序排列。

示例:

SQL33 找出每个学校GPA最低的同学

题目:现在运营想要找到每个学校gpa最低的同学来做调研,请你取出每个学校的最低gpa。

示例:user_profile

iddevice_idgenderageuniversitygpaactive_days_within_30question_cntanswer_cnt
12138male21北京大学3.47212
23214male复旦大学415525
36543female20北京大学3.212330
42315female23浙江大学3.6512
55432male25山东大学3.8201570
62131male28山东大学3.315713
74321female26复旦大学3.69652

根据示例,你的查询结果应参考以下格式,输出结果按university升序排序:

device_iduniversitygpa
6543北京大学3.2000
4321复旦大学3.6000
2131山东大学3.3000
2315浙江大学3.6000
select device_id,university,min(gpa)
from user_profile
group by university;
报错:
SQL_ERROR_INFO: "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'user_profile.device_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by"


可行的正确答案:从排好的表中获取结果
select device_id,university,gpa
from (
    select device_id,university,gpa,
      row_number() over (
        partition by university
        order by gpa
      ) as rk
    from user_profile
  ) as tab
where rk = 1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值