gpt4 book ai didi

sql - 如何计算运行 SUM?

转载 作者:IT王子 更新时间:2023-10-29 06:21:35 24 4
gpt4 key购买 nike

我如何得到一个列是另一列前面值的总和?

最佳答案

从 SQLite 3.25.0 开始,自 2018 年 9 月 15 日起,window functions及其关键字 OVER 均受支持。您的问题的答案现在很简单:

SELECT Country, Gdp, SUM(Gdp) OVER (ROWS UNBOUNDED PRECEDING)
FROM CountryGdp;

这是执行您请求的最小查询,但它没有定义任何顺序,因此这是一种更合适的执行方式。

SELECT
Country,
Gdp,
SUM(Gdp) OVER (
ORDER BY Country -- Window ordering (not necessarily the same as result ordering!)
ROWS BETWEEN -- Window for the SUM includes these rows:
UNBOUNDED PRECEDING -- all rows before current one in window ordering
AND CURRENT ROW -- up to and including current row.
) AS RunningTotal
FROM CountryGdp
ORDER BY Country;

无论如何,查询应该在 O(N) 时间内运行。

关于sql - 如何计算运行 SUM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5606560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com