我有一个Oracle DB,其中包含几列。其中两个包含不同的预订号。 “ Key1”和“ Key2”。如果“ Key2”包含数字(<> 0),则将其声明为更正。因此,“ Key1”上的相同数字是固定的-应该删除。
我认为加入是删除更正预订和相应的“ Key1”的完美方法,或者是一种优雅的方法。
如何在此代码中实现“左反连接”:
SELECT
replace(to_char("Start", '00,00,00'),',',':') as "tStart",
"Key1" as "Key1",
"Key2" as "Key2",
"Value" as "Value",
"Date" as "Date",
"Dep" as "Dep"
FROM "POOL112"."IKZ99H"
WHERE "Value" >950
AND "Dep" = 1
还是您有一个更合适的解决方案/主意?
答案 0 :(得分:1)
我认为以下查询将“过滤掉”您不想显示的行:
with
x as (
select key1, key2 from pool112.ikz99h where key2 <> 0
)
select * -- all my columns here
from pool112.ikz99h
where value > 950
and dep = 1
and key1 not in (select key1 from x) -- filtering out obsolete rows
and key2 not in (select key2 from x) -- filtering out superseding rows
答案 1 :(得分:1)
因此Key1不应在另一个记录中作为Key2存在吗?
SELECT
REPLACE(TO_CHAR("Start", '00,00,00'),',',':') as "tStart",
Key1, Key2, "Value", "Date", Dep
FROM "POOL112"."IKZ99H" t
WHERE "Value" > 950
AND Dep = 1
AND NOT EXISTS
(
SELECT *
FROM "POOL112"."IKZ99H" d
WHERE d.Key2 = t.Key1
AND d.Key1 <> d.Key2
)
或者通过将LEFT JOIN与NULL检查一起使用。
SELECT
REPLACE(TO_CHAR(t."Start", '00,00,00'),',',':') as "tStart",
t.Key1, t.Key2, t."Value", t."Date", t.Dep
FROM "POOL112"."IKZ99H" t
LEFT JOIN "POOL112"."IKZ99H" d ON (d.Key2 = t.Key1 AND d.Key1 <> d.Key2)
WHERE t."Value" > 950
AND t.Dep = 1
AND d.Key2 IS NULL