在SQL查询中使用Not in

时间:2018-06-07 05:09:46

标签: sql oracle

我有两个表billcrown和bank_details。 在billcrown中,每个PJNO都有一个唯一的行:

PJNO GRIRNO AMT
---- ------ ----
PJ1   GRIR1 1000
PJ2   GRIR2 150

表bankdetails有

PJNO GRIRNO AMT
---- ------ ---
PJ1  GRIR1  100
PJ2  GRIR2  150 
PJ1  GRIR1  200

我想要显示表billcrown的所有PJNO,其中这个PJNO在银行细节中的AMT之和不等于这个PJNO在billcrown中的AMT

此处的billcrown数量中的PJ1为1000,但PJ1的bankdetails中的金额总和为300.因此应该显示。但是在PJ2的情况下,billcrown和bankdetails的数量是相同的。

5 个答案:

答案 0 :(得分:2)

也许是这样的事情?

select c.pjno
from billcrowm c join bankdetails d on d.pjno = c.pjno
group by c.pjno
having sum(c.amt) <> sum(d.amt);  

[编辑,新信息披露后]

与NVL的外部联接可能会起作用。

select c.pjno
from billcrowm c left join bankdetails d on c.pjno = d.pjno
group by c.pjno
having sum(c.amt) <> nvl(sum(d.amt), 0);

[编辑#2,阅读Sharad的评论后]

with csum as 
  (select pjno, grirno, sum(amt) amt
   from billcrowm
   group by pjno, grirno
  ),
dsum as
  (select pjno, grirno, sum(amt) amt
   from bankdetails
   group by pjno, grirno
  )
select c.pjno
from csum c left join dsum d on c.pjno = d.pjno
group by c.pjno
having sum(c.amt) <> sum(nvl(d.amt, 0));

答案 1 :(得分:1)

SELECT b.PJNO FROM billcrowm b
LEFT JOIN 
(
    SELECT PJNO, sum(amt) AS total_amt FROM bankdetails GROUP BY PJNO
)d
ON b.PJNO = d.PJNO
WHERE COALESCE(b.amt,0) <> COALESCE(d.total_amt,0);

答案 2 :(得分:0)

IF OBJECT_ID('tempdb..#myTemp') IS NOT NULL
  DROP TABLE #myTemp

SELECT * INTO #myTemp FROM 
 (SELECT PJNO, SUM(AMT) AS Amount FROM 
 bankdetails 
 GROUP BY PJNO)
 AS tempResult

SELECT T.[PJNO], T.Amount, (T1.AMT - T.Amount) As AmountDiff
FROM #myTemp T
INNER JOIN  billcrowm  T1 ON T.[PJNO] = T1.[PJNO]
WHERE T.Amount <> T1.AMT

答案 3 :(得分:0)

这样可行。

with BankDetailsCTE 
as
(
Select PJNO, sum(AMT) as amt from BankDetails group by PJNO
)
Select d.Pjno from Billcrown d 
left join BankDetailsCTE c
on d.pjno = c.pjno
where d.AMT <> c.amt or c.amt is null

答案 4 :(得分:0)

如果我理解得很清楚,您只需要GROUP BY OUTER JOIN

使用这些表格:

create table billcrown (PJNO, GRIRNO, AMT) as (
select 'PJ1', 'GRIR1', 1000 from dual union
select 'PJ2', 'GRIR2',  150 from dual union
select 'PJXX','XXXXX',  100 from dual
);
create table bankdetails (PJNO, GRIRNO, AMT) as (
select 'PJ1',  'GRIR1',  100 from dual union 
select 'PJ2',  'GRIR2',  150 from dual union  
select 'PJ1',  'GRIR1',  200 from dual
);

select bc.PJNO, bc.GRIRNO, bc.AMT, sum(bd.amt) 
from billCrown bc
        left join bankDetails bd
        on (bd.PJNO = bc.PJNO
            and bd.GRIRNO = bc.GRIRNO -- do you need this?
           )
group by bc.PJNO, bc.GRIRNO, bc.AMT
having sum(nvl(bd.amt, 0)) != bc.amt

给出:

PJNO GRIRNO        AMT SUM(BD.AMT)
---- ------ ---------- -----------
PJXX XXXXX         100            
PJ1  GRIR1        1000         300