[英]My code is not comparing every row in Oracle
以下是我的代碼,我想選擇不存在於第二個表中
select t.reg,
t.dist,
t.pkey,
t.n_code,
t.sum as s17,
s.sum as s18
from table1 t,
(select *
from table2 t
where t.pkey is not null) s
where t.pkey= s.pkey
and t.reg= s.reg
and t.dist= s.dist
and t.a = 99
and s.a != 99
and t.n_code= 66
and t.n_code = s.n_code
and t.sum > 0
and t.sum not in s.sum --not in is not working i think
and t.reg= 33
and t.dist= 1
t.sum 不在第二個表中的每一行中進行比較,第一個表中的值存在於第二個表中,而是在另一行中。
代碼不搜索其他行以及PL/SQL
Not in
這樣不行。 Not in
語法是t.sum Not in (10,20)
,您也可以使用子查詢代替靜態值。
但這里Not In
不需要。 您可以替換以下內容
and t.sum not in s.sum
和
and t.sum <> s.sum
這樣的事情會有幫助嗎? 帶有顯式連接和條件的更漂亮的代碼移至where
子句。
select t.reg,
t.dist,
t.pkey,
t.n_code,
t.sum as s17,
s.sum as s18
from table1 t join table2 s
on t.pkey= s.pkey
and t.reg= s.reg
and t.dist= s.dist
and t.n_code = s.n_code
and t.sum <> s.sum --> this
where t.pkey is not null
and t.a = 99
and s.a != 99
and t.n_code= 66
and t.sum > 0
and t.reg= 33
and t.dist= 1
您可以使用not exists
,但更快的是添加條件count()
檢查總和是否相同(在整個窗口中)。 如果此 count<>0 從輸出中刪除行。
select reg, dist, pkey, n_code, s17, s18
from (
select t.reg, t.dist, t.pkey, t.n_code, t.sum as s17, s.sum as s18,
count(case when t.sum = s.sum then 1 end)
over (partition by t.pkey, t.reg, t.dist, t.n_code) cnt_same
from table1 t
join (select * from table2 t where t.pkey is not null) s
on t.pkey = s.pkey and t.reg = s.reg and t.dist = s.dist and t.n_code = s.n_code
where t.a = 99 and s.a != 99 and t.n_code= 66
and t.sum > 0 and t.reg= 33 and t.dist = 1)
where cnt_same = 0
這部分很重要:
over (partition by t.pkey, t.reg, t.dist, t.n_code)
它確定我們在哪個范圍內檢查和。 如果要掃描整個表,請使用:
over ()
如果你只想使用相同的 pkey
over (partition by t.pkey)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.