当前位置:   article > 正文

sql over(partition by) 开窗函数的使用_sql over part

sql over part

patition by  在group by分组汇总的前提下,再汇总一次

  1. create table student_score
  2. (
  3. id serial,
  4. class varchar(54),
  5. name varchar(54),
  6. subject varchar(54),
  7. score float
  8. );
  9. create unique index student_score_id_uindex
  10. on student_score (id);
  11. alter table student_score
  12. add constraint student_score_pk
  13. primary key (id);
  14. insert into student_score(class, name, subject, score)
  15. values ('一年级1班', '小明', '语文', 100.0),
  16. ('一年级1班', '小明', '英语', 80.0),
  17. ('一年级1班', '小明', '数学', 90.0),
  18. ('一年级1班', '小红', '语文', 98.0),
  19. ('一年级1班', '小红', '数学', 85.0),
  20. ('一年级1班', '小红', '英语', 90.0),
  21. ('一年级2班', '小夏', '语文', 88.0),
  22. ('一年级2班', '小夏', '数学', 85.0),
  23. ('一年级2班', '小夏', '英语', 89.0),
  24. ('一年级2班', '小黄', '语文', 70.0),
  25. ('一年级2班', '小黄', '数学', 88.0),
  26. ('一年级2班', '小黄', '英语', 67.0);
  27. truncate student_score;
  28. -- 窗口函数over 表示在...范围内
  29. -- partition by 1 可以理解为将他们都归到一个分组里面
  30. -- partition by name 是根据name再次进行分组,然后统计总分
  31. select class,
  32. name,
  33. sum(score) 个人总分,
  34. sum(sum(score)) over (partition by name) 个人总分,
  35. sum(sum(score)) over (partition by class) 班级总分,
  36. sum(sum(score)) over (partition by 1) 年级总分
  37. from student_score
  38. group by class, name;
  39. select name,
  40. sum(score) 个人总分,
  41. sum(sum(score)) over (partition by 1) 年级总分
  42. from student_score
  43. group by name;

 

1、patition by 1   汇总所有数据

 1 select * from stu 

  1. select
  2. class,
  3. sum(score) 班级总分,
  4. sum(sum(score)) over(partition by 1) 年级总分,
  5. cast(cast(sum(score)*100/nullif(sum(sum(score)) over(partition by 1),0) as numeric(18,2)) as varchar(50))+'%' as 班级总分占比
  6. from stu
  7. group by class

2、patition by 字段   根据该字段汇总

 1 select * from stu 

  1. select
  2. class,
  3. name,
  4. sum(score) 个人总分,
  5. sum(sum(score)) over(partition by name) 个人总分,
  6. sum(sum(score)) over(partition by class) 班级总分,
  7. sum(sum(score)) over(partition by 1) 年级总分
  8. from stu
  9. group by class,name

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/241174
推荐阅读
相关标签
  

闽ICP备14008679号