oracle 使用任何联接时复制记录

s2j5cfk0  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(172)

我有两个表。第一个表有一个正值,第二个表有一个负值。就像这样

我进行了测试,根据trx_number合并两个表,得出SUM(positive.nett)和SUM(negative.nett)的合计,然后合并得出总计(SUM positive + SUM negative)

SELECT p.trx_number,
       SUM(p.nett) total1,
       SUM(n.nett) total2
  FROM positif p
  FULL JOIN negatif n
    ON p.trx_number = n.trx_number
 GROUP BY p.trx_number

但结果就这样

我意识到数字3(trx_id)有一个重复的结果,数字3的结果应该是正负之间的同一个数字。我尝试修复这个问题,但仍然不起作用。
请帮我这个忙

kpbwa7wx

kpbwa7wx1#

使用内部联接,并在联接表之前使用GROUP BY *。

示例

create table positif ( trx, nett )
as 
select 3, 2147600 from dual union all
select 3, 2068300 from dual union all
select 4, 50000   from dual union all
select 5, 100000  from dual ;

create table negatif ( trx, nett )
as
select 3, -1073800 from dual union all
select 3, -1073800 from dual union all
select 3, -2068300 from dual union all
select 4, -20000   from dual union all
select 5, -100000  from dual ;

查询

select P.trx, P.sum_ totalpos, N.sum_ totalneg
from 
  ( select trx, sum( nett ) sum_ from positif group by trx ) P
  join
  ( select trx, sum( nett ) sum_ from negatif group by trx ) N
  on P.trx = N.trx 
order by 1
;

-- result
TRX TOTALPOS    TOTALNEG
3   4215900     -4215900
4   50000       -20000
5   100000      -100000

DBfiddle
完全联接的主要问题是返回的行太多。例如,尝试只联接TRX列-〉您将得到2乘以3(6)行。您需要的是:每个TRX值占一行。(因此,在联接之前进行分组。)
行太多...

select P.trx
from positif P full join negatif N on P.trx = N.trx ;

TRX
3
3
3
3
3
3
4
5

备选方案:您也可以使用UNION ALL,然后使用GROUP BY(和sum),例如
所有接头

select trx, nett as pos, null as neg from positif
union all
select trx, null, nett from negatif ;

-- result
TRX POS     NEG
3   2147600 null
3   2068300 null
4   50000   null
5   100000  null
3   null    -1073800
3   null    -1073800
3   null    -2068300
4   null    -20000
5   null    -100000

GROUP BY和SUM

select trx 
, sum ( pos ) totalpos, sum( neg ) totalneg 
from (
  select trx, nett as pos, null as neg from positif
  union all
  select trx, null, nett from negatif 
) 
group by trx 
order by 1 ;

-- result
TRX TOTALPOS    TOTALNEG
3   4215900 -4215900
4   50000   -20000
5   100000  -100000

相关问题