2016-07-25 29 views
-2

我需要一些可以跳過「對」並且只選擇非配對數據的Oracle查詢的幫助。例如:可以過濾配對數據的Oracle查詢

Id  cost hour type 
123  $1.00 1 Input 
123  $1.00 1 Output 

234  $2.00 4 Input 
345  $5.00 4 Output 

236  $3.00 5 Input 
236  $3.00 3 Output 

在這個例子中,前兩行是'pair',因爲前3個字段匹配;第三和第四,第五和第六行不是「一對」,因爲它們的前三個字段不匹配。

+2

但是...但是...如果第二行與第一行相同,它們都顯示INPUT,並且沒有輸出id = 123,cost = $ 1.00,hour = 1呢?他們還是一對嗎?或者你需要給出一個更好/更準確的解釋什麼是「一對」?還有一個問題:如果你有兩行與你給出的第一行(輸入)相同,並且只有一行與輸出相同?是否有「一對」,然後您仍然需要選擇「僅輸入」行的一個副本? – mathguy

+0

該對是前3個屬性匹配的「輸入」和「輸出」(示例中的前2條記錄) - 接下來的兩組不匹配 - 是的,我需要那些沒有「輸入」或「輸出」 '將與無與倫比的'雙'一起報告 - 再次感謝澄清。希望我已經解釋清楚了 – user3096366

回答

0

您可以通過

select id, cost, hour, type 
    from (
    select id, cost, hour, type, 
     count(*) over(partition by id, cost, hour) as cn 
    from mytable) t 
where cn=1; 
+0

非常感謝,讓我試試 – user3096366

+0

@ user3096366在閱讀Mathguys評論後,我不知道這是不是您要找的內容。 – vercelli

+1

沒錯 - 我想要第一對被跳過,只有2和3(在這個例子中)報告。謝謝韋爾切利 – user3096366

0

使用窗函數和分區我改列名「小時」到「小時」和「類型」爲「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. 
0

lag()分析功能就足夠了。

select * from stackovf svf where id not in (select id from (select svf.*, 
    (case when lag(id) over (partition by id,cost,hour order by 1)=id 
    and lag(cost) over (partition by id,cost,hour order by 1)=cost 
    and lag(hour) over (partition by id,cost,hour order by 1)=hour then 1 
    else 0 end)as match_found 
    from stackovf svf) 
    where match_found=1)