Oracle SQL 循环遍历相同的数据并基于当前日期

斯特凡

我试图根据日期使用 oracle SQL 多次选择相同的数据。

例如,目前我写了这个 SQL 查询来计算我在当前日期的余额:

select to_char(sysdate, 'DD-MM-YYYY') date,
(
select (   
            select NVL(sum(bedrag), 0) bedrag
                from transactie 
                where rekening_naar_id = r.id
                and datum <= sysdate
                and actief = 1

        )  
        -  
        (
            select NVL(sum(bedrag), 0) bedrag
                from transactie 
                where rekening_van_id = r.id
                and datum <= sysdate
                and actief = 1
        ) 
    from dual     
    ) 
as balance
from rekening r
where r.id = 2; 

我想知道是否可以在单个 SQL 查询中多次循环遍历相同的数据并选择多行,每次只将日期增加 1 天?余额根据显示在图表中的日期而变化。

我无法将 PL/SQL 用于此查询,因为我需要在 Oracle Apex 图表中填充数据,并且没有使用 PL/SQL 生成图表的选项。只允许有效的 SQL 查询或返回有效 SQL 查询的 PL/SQL 代码。

kfinity

当您想到“Oracle SQL 中的循环”时,请考虑connect by level.

这个例子是未来 30 天。

select d.date1,
(
select (   
            select NVL(sum(bedrag), 0) bedrag
                from transactie 
                where rekening_naar_id = r.id
                and datum <= d.date1
                and actief = 1

        )  
        -  
        (
            select NVL(sum(bedrag), 0) bedrag
                from transactie 
                where rekening_van_id = r.id
                and datum <= d.date1
                and actief = 1
        ) 
    from dual     
    ) 
as balance
from rekening r
cross join (select trunc(sysdate+(level-1)) as date1
    from dual
    connect by level < 31) d
where r.id = 2; 

sqlfiddle

交叉连接是一样的纯join my_table没有加入的条件下,或join my_table on 1=1它返回两个表中行的所有组合。在这种情况下,它返回行的所有组合rekening与行中内嵌视图命名d(其中包含日期在接下来的30天)。尝试单独运行d视图的 select 语句以查看它的作用。

select trunc(sysdate+(level-1)) as date1
from dual
connect by level < 31;

按级别连接是分层connect by子句的特例它生成一系列行/数字,这非常有用。这是一个非常简单的例子:

select level from dual connect by level < 10;

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章