先看下我找的题目,ENG OMG 放心 我给安排了中文
The cats must be ordered first by breed and second by name. They are about to enter an elevator one by one. When all the cats of the same breed have entered they leave.
We would like to know what the running total weight of the cats is.
Return: name, breed, running total weight
Order by: breed, name
name | breed | running_total_weight |
---|---|---|
Charlie | British Shorthair | 4.8 |
Smudge | British Shorthair | 9.7 |
Tigger | British Shorthair | 13.5 |
Millie | Maine Coon | 5.4 |
Misty | Maine Coon | 11.1 |
Puss | Maine Coon | 16.2 |
Smokey | Maine Coon | 22.3 |
Ashes | Persian | 4.5 |
Felix | Persian | 9.5 |
Molly | Persian | 13.7 |
Alfie | Siamese | 5.5 |
Oscar | Siamese | 11.6 |
分区运行总数
问题:
猫必须先按品种,后按名字订购。他们正要一个接一个地走进电梯。当所有同品种的猫都进入后,它们就离开。
我们想知道猫的跑步总重量是多少。
期望的输出:
name | breed | running_total_weight |
---|---|---|
Charlie | British Shorthair | 4.8 |
Smudge | British Shorthair | 9.7 |
Tigger | British Shorthair | 13.5 |
Millie | Maine Coon | 5.4 |
Misty | Maine Coon | 11.1 |
Puss | Maine Coon | 16.2 |
Smokey | Maine Coon | 22.3 |
Ashes | Persian | 4.5 |
Felix | Persian | 9.5 |
Molly | Persian | 13.7 |
Alfie | Siamese | 5.5 |
Oscar | Siamese | 11.6 |
答案:
select
name,
breed,
sum(weight) over (partition by breed order by name asc) as running_total_weight
from
cats
答案完全正确哦,哈哈哈 !
丝路输出:
最近工作用的太多了,踩坑也多,所以一下就做出来了。
我首先看到根据猫的品牌进行区分,每组猫进去后就出去,然后每组猫需要正序排序。
所以按照品牌分区、猫名正序、SUM() + OVER() 就可以完成
这里最主要是利用了开窗函数中添加排序后的特性:具体 默认order的开窗函数frame值是
between UNBOUNDED PRECEDING and CURRENT ROW
译文:第一行 -》 当前行
所以每次排序后我SUM函数取得是本品牌中排名第一的猫 - 当前猫的重量和!
你学费了么?
练习题的地址“戳我”
我们还有开窗的下一期哦