plsql同一个表中具有不同日期的相同数据

fcwjkofz  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(469)

我在oracle中有一个表,我想得到sysdate的借方和贷方列之和的差,以及6个月前借方和贷方列之和的差
我的问题是

select a.name,a.id, nvl(sum(a.debit),0)-nvl(sum(a.credit),0) current_bal
from mytable a
where a.id='1092' and a.docdate<=sysdate
group by a.name,a.id
union
select b.name,b.id,nvl(sum(b.debit),0)-nvl(sum(b.credit),0) current_bal1
from mytable b
where b. id='1092' and b.docdate<=add_months(sysdate,-6)
group by b.name,b.id;

我得到了正确的结果,但是查询返回了两行,其中我需要将这个结果显示为一行。
请对我的问题提出任何建议/更正。

tkqqtvp1

tkqqtvp11#

可以按如下方式使用条件聚合:

select a.name,a.id, nvl(sum(CASE WHEN a.docdate<=sysdate THEN a.debit END),0)-nvl(sum(CASE WHEN a.docdate<=sysdate THEN a.credit END),0) current_bal,
nvl(sum(CASE WHEN b.docdate<=add_months(sysdate,-6) THEN a.debit END),0)-nvl(sum(CASE WHEN b.docdate<=add_months(sysdate,-6) THEN a.credit END),0) current_bal1
from mytable a
where a.id='1092'
group by a.name,a.id;

--更新
如果您面临任何问题,那么最简单的方法就是在子查询之间使用self-join,如下所示:

SELECT A.NAME, A.ID, A.CURRENT_BAL, B.CURRENT_BAL1
FROM
(select a.name,a.id, nvl(sum(a.debit),0)-nvl(sum(a.credit),0) current_bal
from mytable a
where a.id='1092' and a.docdate<=sysdate
group by a.name,a.id) A
JOIN 
(select b.name,b.id,nvl(sum(b.debit),0)-nvl(sum(b.credit),0) current_bal1
from mytable b
where b. id='1092' and b.docdate<=add_months(sysdate,-6)
group by b.name,b.id) B
ON A.ID = B.ID AND A.NAME = B.NAME;
voase2hg

voase2hg2#

可以使用条件聚合:

select a.name, a.id, 
       coalesce(sum(a.debit), 0) - coalesce(sum(a.credit), 0) as current_bal,
       (sum(case when a.docdate < add_months(sysdate, -6) then a.debit else 0 end) -
        sum(case when a.docdate < add_months(sysdate, -6) then a.credit else 0 end)
       ) as bal_6_months
from mytable a
where a.id = '1092' and a.docdate <= sysdate
group by a.name, a.id;

这将两个值放在同一行中。这对我来说似乎比把它们放在不同的一排更有用。

jv2fixgn

jv2fixgn3#

你能试试吗:

select a.name,a.id, LISTAGG(nvl(sum(a.debit),0)-nvl(sum(a.credit),0), ' ') WITHIN GROUP (ORDER BY a.id) current_bal
from mytable a
where a.id='1092' and a.docdate<=sysdate
group by a.name,a.id
union
select b.name,b.id, LISTAGG(nvl(sum(a.debit),0)-nvl(sum(a.credit),0), ' ') WITHIN GROUP (ORDER BY a.id) current_bal
from mytable b
where b. id='1092' and b.docdate<=add_months(sysdate,-6)
group by b.name,b.id;

相关问题