1

我正在尝试根据日期使用 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 代码。

4

1 回答 1

1

当您想到“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的行(其中包含未来 30 天的日期)。尝试自己运行视图的 select 语句,看看它做了什么。dd

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

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

select level from dual connect by level < 10;
于 2017-11-08T16:44:54.783 回答