开窗函数

---恢复内容开始---

例子

将成绩表中总成绩最大的考生分数记录标记出

常见错误代码1

1 select s#,
2            score,
3         case when score=max(score)
4             then '表内最大值'
5                 else ''
6                     end,
7     from sc
8     group by s#

 

错误原因:s#未包含在group by子句中

常见错误代码2

1 select s#,
2            score,
3         case when score=max(score)
4             then '表内最大值'
5                 else ''
6                     end,
7     from sc
8     group by s#,score

错误原因:group by子句破坏原有的分组

设想解决方法

使用聚合函数而不必将select列表中的所有列都放入group by子句中

正确代码1

1 select s#,
2             score
3             case when score=max(score)over (partition by s#)
4             then '表内最大值'
5             else
6             end,
7     from sc

适用范围:折尺开窗函数的DBMS

正确代码2

select s#,
score,
case wnen score=(select max(score) from sc S_2 when s_2.s#=s_1.s#)
then '表内最大值'
else ''
end,
from sc s_1

 

---恢复内容结束---

例子

将成绩表中总成绩最大的考生分数记录标记出

常见错误代码1

1 select s#,
2            score,
3         case when score=max(score)
4             then '表内最大值'
5                 else ''
6                     end,
7     from sc
8     group by s#

 

错误原因:s#未包含在group by子句中

常见错误代码2

1 select s#,
2            score,
3         case when score=max(score)
4             then '表内最大值'
5                 else ''
6                     end,
7     from sc
8     group by s#,score

错误原因:group by子句破坏原有的分组

设想解决方法

使用聚合函数而不必将select列表中的所有列都放入group by子句中

正确代码1

1 select s#,
2             score
3             case when score=max(score)over (partition by s#)
4             then '表内最大值'
5             else
6             end,
7     from sc

适用范围:折尺开窗函数的DBMS

正确代码2

select s#,
score,
case wnen score=(select max(score) from sc S_2 when s_2.s#=s_1.s#)
then '表内最大值'
else ''
end,
from sc s_1

解释

1.开窗函数:over()

2.partition by子句:创建独立于结果集的分区

3.order by子句:

order by 字段名 rang|row between 边界规则1 and 边界规则2

 4.开窗函数只能出现在 SELECT 或 ORDER BY 子句中。

参考:https://blog.csdn.net/qq814965130/article/details/79479081

posted @ 2019-06-05 06:12  甜汤  阅读(691)  评论(0编辑  收藏  举报