Oracle SQL 循环遍历相同的数据并将其基于当前日期
Oracle SQL loop through the same data and base it on the current date
我正在尝试根据日期使用 oracle SQL 多次 select 相同的数据。
例如,目前我写了这个 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 查询和 select 多行中多次循环遍历同一数据,每次只是将日期增加 1 天?余额根据日期变化以显示在图表中。
我无法使用 PL/SQL 进行此查询,因为我需要将数据填充到 Oracle Apex 图表中,但没有使用 PL/SQL 生成图表的选项。仅允许有效 SQL 查询或 PL/SQL 代码 returns 有效 SQL 查询。
想"loop in 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;
交叉连接 与没有连接条件的普通 join my_table
或 join my_table on 1=1
相同。它 returns 两个表中行的所有组合。在这种情况下,它 returns rekening
中的所有行与 内联视图 中名为 d
的行的所有组合(其中包含接下来 30天)。单独尝试 运行 d
视图的 select 语句,看看它做了什么。
select trunc(sysdate+(level-1)) as date1
from dual
connect by level < 31;
按级别连接 是分层connect by
子句的特例。它生成一个 rows/numbers 的序列,这可能非常有用。这是一个非常简单的例子:
select level from dual connect by level < 10;
我正在尝试根据日期使用 oracle SQL 多次 select 相同的数据。
例如,目前我写了这个 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 查询和 select 多行中多次循环遍历同一数据,每次只是将日期增加 1 天?余额根据日期变化以显示在图表中。
我无法使用 PL/SQL 进行此查询,因为我需要将数据填充到 Oracle Apex 图表中,但没有使用 PL/SQL 生成图表的选项。仅允许有效 SQL 查询或 PL/SQL 代码 returns 有效 SQL 查询。
想"loop in 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;
交叉连接 与没有连接条件的普通 join my_table
或 join my_table on 1=1
相同。它 returns 两个表中行的所有组合。在这种情况下,它 returns rekening
中的所有行与 内联视图 中名为 d
的行的所有组合(其中包含接下来 30天)。单独尝试 运行 d
视图的 select 语句,看看它做了什么。
select trunc(sysdate+(level-1)) as date1
from dual
connect by level < 31;
按级别连接 是分层connect by
子句的特例。它生成一个 rows/numbers 的序列,这可能非常有用。这是一个非常简单的例子:
select level from dual connect by level < 10;