使用窗函數和分區我改列名「小時」到「小時」和「類型」爲「type_」(這是不好用保留的甲骨文字作爲對象名稱,包括列名)。我假設成本是以數字給出的,而不是顯示的$符號。 (如果它是一個字符串,這是一個壞主意,開始使用。)
with
input_data (id, cost, hours, type_) as (
select 123, 1.00, 1, 'Input' from dual union all
select 123, 1.00, 1, 'Output' from dual union all
select 234, 2.00, 4, 'Input' from dual union all
select 345, 5.00, 4, 'Output' from dual union all
select 236, 3.00, 5, 'Input' from dual union all
select 236, 3.00, 3, 'Output' from dual
),
prep (id, cost, hours, type_, rn, pairs) as (
select id, cost, hours, type_,
row_number() over (partition by id, cost, hours, type_ order by null),
least (count(case when type_ = 'Input' then 1 end)
over (partition by id, cost, hours),
count(case when type_ = 'Output' then 1 end)
over (partition by id, cost, hours)
)
from input_data
)
select id, cost, hours, type_
from prep
where rn > pairs
;
row_number()
計數固定ID,成本,時間和type_行(我不在乎什麼樣的順序,我只需要他們「列舉「)並且pairs
計數有多少對。在最後的選擇中,我只保留row_number大於pairs
的行 - 這正是您所需要的。
ID COST HOURS TYPE_
---------- ---------- ---------- ------
234 2 4 Input
236 3 3 Output
236 3 5 Input
345 5 4 Output
4 rows selected.
但是...但是...如果第二行與第一行相同,它們都顯示INPUT,並且沒有輸出id = 123,cost = $ 1.00,hour = 1呢?他們還是一對嗎?或者你需要給出一個更好/更準確的解釋什麼是「一對」?還有一個問題:如果你有兩行與你給出的第一行(輸入)相同,並且只有一行與輸出相同?是否有「一對」,然後您仍然需要選擇「僅輸入」行的一個副本? – mathguy
該對是前3個屬性匹配的「輸入」和「輸出」(示例中的前2條記錄) - 接下來的兩組不匹配 - 是的,我需要那些沒有「輸入」或「輸出」 '將與無與倫比的'雙'一起報告 - 再次感謝澄清。希望我已經解釋清楚了 – user3096366