gpt4 book ai didi

sql - oracle查询余额

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:35 25 4
gpt4 key购买 nike

我想选择最近两天(今天和昨天)的余额,代码看起来像这样

select a.balance as "today",b.balance as "yesterday"
from account a,account b
where a.id='xxx'
and a.id=b.id
and a.dates=to_date(sysdate, 'DD-MM-YYYY') --today
and b.dates=to_date(sysdate-1, 'DD-MM-YYYY') --yesterday

当今天的数据还没有输入时,问题就来了。即使昨天的数据可用,这也会导致两个余额为空

注意:我目前的解决方案是将查询分成 2 个。但我希望有任何方法可以只使用 1 个查询

预期输出

-----------------
|today|yesterday|
-----------------
|null |9000 |
-----------------

数据

--------------------------
|id |balance |dates |
--------------------------
|1 |9000 |6/5/2015|
--------------------------

最佳答案

无需加入,使用LAG函数追踪上一个。
如果您想了解滞后功能。请访问以下链接。 http://www.techonthenet.com/oracle/functions/lag.php .我已将以下内容作为输入。 enter image description here

并使用自动跟踪前一行的滞后执行下面的查询。

选择 * 从 (
SELECT ID,LAG(BALANCE) OVER (ORDER BY DATES) AS YESTERDAY_BALANCE,BALANCE AS TODAYS_BALANCE
来自账户)
WHERE YESTERDAY_BALANCE 不为空;

我得到的输出如下。如果您仍然无法获取今天的数据,它将显示该行。
enter image description here

关于sql - oracle查询余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092020/

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