PLSQL同表不同日期的相同数据。

问题描述 投票:0回答:1

我在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;

我得到了正确的结果,但查询返回的是两行,而我需要的是将结果显示为单行。

任何建议纠正我的查询,请。

sql database oracle plsql union-all
1个回答
0
投票

你可以使用条件聚合,如下所示。

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;

-- 更新

如果你面临任何问题,那么最简单的方法是使用子查询之间的自连接,如下所示。

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;

0
投票

你可以使用条件聚合。

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;

这样可以把两个值放在同一条记录里 在我看来,这比把它们放在不同的行中更有用。


0
投票

你可以尝试一下。

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;
© www.soinside.com 2019 - 2024. All rights reserved.