我们可以修改前一行并在 SQL 查询列表的当前行中使用它吗?
Can we modify the previous row and use it in current row in a SQL query for a list?
我环顾四周,发现了一些包含 LAG() 和 运行 总类型查询的帖子,但 none 似乎符合我的要求。也许我在搜索中没有使用正确的术语,或者我可能使情况变得过于复杂。希望有人能帮帮我。
但我想要做的是获取之前的结果并将其乘以当前行的日期范围。开始总是一些基数让我们做 10 以保持简单。这些值将是浮动的,但我在这里将其保留为整数以更好地解释我的查询。
第一个显示计算部分,下面的第二个 table 显示最终结果应该是什么样子。
date val1 calc_result
20120930 null 10
20121031 2 10*2=20
20121130 3 20*3=60
20121231 1 60*1=60
20130131 2 60*2=120
20130228 1 120*1=120
查询会return
20120930 10
20121031 20
20121130 60
20121231 60
20130131 120
20130228 120
我想看看这是否可以在查询类型的解决方案中完成,或者是否需要使用 PL/SQL table/cursors?
如有任何帮助,我们将不胜感激。
您可以使用递归 CTE 执行此操作:
with dates as (
select t.*, row_number() over (order by date) as seqnum
from t
),
cte as (
select t.date, t.val, 10 as calc_result
from dates t
where t.seqnum = 1
union all
select t.date, t.val, cte.calc_result * t.val
from cte join
dates t
on t.seqnum = cte.seqnum + 1
)
select cte.date, cte.calc_result
from cte
order by cte.date;
这是计算一个累积乘积。你可以用一些指数算法来做到这一点。将查询中的 10
替换为所需的起始值。
select date,val1
,case when row_number() over(order by date) = 1 then 10 --set start value for first row
else 10*exp(sum(ln(val1)) over(order by date)) end as res
from tbl
我环顾四周,发现了一些包含 LAG() 和 运行 总类型查询的帖子,但 none 似乎符合我的要求。也许我在搜索中没有使用正确的术语,或者我可能使情况变得过于复杂。希望有人能帮帮我。
但我想要做的是获取之前的结果并将其乘以当前行的日期范围。开始总是一些基数让我们做 10 以保持简单。这些值将是浮动的,但我在这里将其保留为整数以更好地解释我的查询。
第一个显示计算部分,下面的第二个 table 显示最终结果应该是什么样子。
date val1 calc_result
20120930 null 10
20121031 2 10*2=20
20121130 3 20*3=60
20121231 1 60*1=60
20130131 2 60*2=120
20130228 1 120*1=120
查询会return
20120930 10
20121031 20
20121130 60
20121231 60
20130131 120
20130228 120
我想看看这是否可以在查询类型的解决方案中完成,或者是否需要使用 PL/SQL table/cursors?
如有任何帮助,我们将不胜感激。
您可以使用递归 CTE 执行此操作:
with dates as (
select t.*, row_number() over (order by date) as seqnum
from t
),
cte as (
select t.date, t.val, 10 as calc_result
from dates t
where t.seqnum = 1
union all
select t.date, t.val, cte.calc_result * t.val
from cte join
dates t
on t.seqnum = cte.seqnum + 1
)
select cte.date, cte.calc_result
from cte
order by cte.date;
这是计算一个累积乘积。你可以用一些指数算法来做到这一点。将查询中的 10
替换为所需的起始值。
select date,val1
,case when row_number() over(order by date) = 1 then 10 --set start value for first row
else 10*exp(sum(ln(val1)) over(order by date)) end as res
from tbl