oracle查询余额

时间:2015-05-07 04:36:12

标签: sql database oracle analytics

我想选择过去2天(今天和昨天)的余额,代码看起来像这样

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|
--------------------------

3 个答案:

答案 0 :(得分:3)

无需加入,使用LAG功能跟踪之前的内容 如果您想了解Lag功能。请访问以下链接。 http://www.techonthenet.com/oracle/functions/lag.php。 我把以下作为输入。 enter image description here

并使用滞后执行以下查询,该滞后自动跟踪上一行 SELECT * FROM( SELECT ID,LAG(BALANCE) OVER (ORDER BY DATES) AS YESTERDAY_BALANCE,BALANCE AS TODAYS_BALANCE FROM ACCOUNTS) WHERE YESTERDAY_BALANCE IS NOT NULL;

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

答案 1 :(得分:2)

如果我们允许硬编码两个日期

,则无需加入两个表
--code with sysdate 

with tab as  --dummy data
(
select 1 id,sysdate -level+1 dat,level*1000 balance 
from dual 
connect by     level <=10  
)
--main query
select max(decode(trunc(dat),trunc(SYSDATE),balance)) "today"
      ,max(decode(trunc(dat),trunc(SYSDATE-1),balance)) "yesterday"
from tab t where TRUNC(t.dat) IN (TRUNC(SYSDATE),TRUNC(SYSDATE-1));

--code without sysdate

with tab as
(
 select 1 id,sysdate -level dat,level*1000 balance 
 from dual 
 connect by level <=10
 )
 --main query
 select max(decode(trunc(dat),trunc(SYSDATE),balance)) "today"
      ,max(decode(trunc(dat),trunc(SYSDATE-1),balance)) "yesterday"
from tab t where TRUNC(t.dat) IN (TRUNC(SYSDATE),TRUNC(SYSDATE-1));

sqlfiddle

select 
 max(decode(trunc(dates),trunc(SYSDATE),balance)) "today"
,max(decode(trunc(dates),trunc(SYSDATE-1),balance)) "yesterday"
from account a
where a.id='xxx'
and trunc(a.dates) IN (trunc(sysdate),trunc(sysdate-1));

答案 2 :(得分:1)

我想你昨天要求今天加入。

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

我对旧语法有点生疏,用更现代的说法

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

请注意我是如何将可选表(a)的检查移动到连接条件的,所以无论如何它都会出现。