mysql - Rewrite correlated subquery in SELECT into JOIN statement
问题描述
I have following source table:
CREATE TABLE test
(`step` varchar(1), `cost_time` int, `rank_no` int)
;
INSERT INTO test
(`step`, `cost_time`, `rank_no`)
VALUES
('a', 10, 1),
('b', 20, 2),
('c', 30, 3)
;
and query like this:
select
main.step,
main.cost_time,
main.rank_no,
(select sum(sub.cost_time)
from test sub
where sub.rank_no <= main.rank_no) as total_time
from
test main
and the result is expected:
| step | cost_time | rank_no | total_time |
|------|-----------|---------|------------|
| a | 10 | 1 | 10 |
| b | 20 | 2 | 30 |
| c | 30 | 3 | 60 |
is it possible to rewrite this sql using join
statement and achieve same result?
解决方案
编写此查询的最佳方法是使用累积和:
select main.step, main.cost_time, main.rank_no,
sum(cost_time) over (order by rank_no) as total_time
from test main;
您不能仅使用join
. 您可以使用join
and重写它group by
:
select main.step, main.cost_time, main.rank_no,
sum(sub.cost_time) as total_time
from test main join
test sub
on sub.rank_no <= main.rank_no
group by main.step, main.cost_time, main.rank_no;
但是,我认为相关子查询是一个更好的解决方案。
推荐阅读
- ubuntu - 无法在 ubuntu 服务器上安装 Nginx amplify
- django - django Rest Framework 按日期范围过滤
- hash - 密码的散列函数
- javascript - 如何运行 JavaScript 文件中的第一个函数?
- swagger - Swagger 正在渲染一个枚举的值,而不是项目中的所有其他枚举
- scala - 如何计算 2 个列表中元素出现的乘积?
- c# - C# ASPX 页面可以直接访问类方法吗?
- ios - 从哪里获取 Linphone iOS SDK 中录制的通话音频文件
- android - Android NDK.Build 命令失败。未定义参考。clang++:错误:链接器命令失败,退出代码为 1
- bash - 为什么通过 Crontab 启动的脚本表现不同?