我在oracle数据库中有一个如下表:
s_num eff_date amount
1 07-OCT-18 110
1 06-OCT-18 50
2 07-OCT-18 200
2 06-OCT-18 150
我想找到今天和昨天的“金额”列之间的区别。结果必须如下所示
s_num diff
1 60
2 50
我想做到这一点而无需将表自身连接起来。
答案 0 :(得分:5)
您可以使用条件聚合
SELECT s_num,SUM (CASE
WHEN eff_date >= TRUNC(sysdate)
AND eff_date < TRUNC(sysdate) + 1 THEN amount --today
WHEN eff_date >= TRUNC(sysdate) - 1
AND eff_date < TRUNC(sysdate) THEN - amount --yesterday
END)
FROM t
GROUP BY s_num;
或LAG
函数
SELECT s_num,
diff
FROM (SELECT s_num,
eff_date,
amount - LAG(amount, 1, 0)
OVER (
partition BY s_num
ORDER BY eff_date ) AS diff
FROM t)
WHERE eff_date >= trunc(sysdate)
AND eff_date < trunc(sysdate) + 1 ;
除了今天以外,第一个会打印NULL
差额,第二个不会为其他日期返回任何行。
答案 1 :(得分:-1)
sql>set serveroutput on;
sql>create or replace function difference(n in number) return number as di
number(5);
2 begin
3 select ((select amount from oc where dob=trunc(sysdate) and snum=n)-
(select
amount from oc where dob=trunc(sysdate-1) and snum=n)) into di from dual;
4 return di;
5 end;
6 /
sql>select distinct snum,difference(snum) as diff from oc;
输出:
SNUM DIFF
---------- ----------
2 50
1 60