2016-09-20 133 views
0

我的表查詢中的列不具有在另一列的值相同

ItemCode  ItemName  Total 
---------------------------------- 
A    name1   5 
A    name1   5 
A    name2   10 
B    name1   10 
B    name2   25 
B    name1   30 
C    name2   5 
C    name1   30 
C    name1   20 

我想顯示所有itemcodeAB不具有在列的值相同Total

我的預期結果

ItemCode   ItemName   Total 
---------------------------------------- 
A     name1    5 
A     name1    5 
B     name2    25 
B     name1    30 

我已經問過這個問題,但這次我的問題比我最後的問題要清楚得多它在。我認爲這是一個自我加入的解決方案,但我無法弄清楚。任何幫助對我來說都意味着很多,謝謝!

+1

對我仍然沒有這麼清楚:爲什麼預期結果中ItemCode ='A'的行?它們來自完全相同的行,具有相同的Total,而您說「在Total列中沒有相同的值」。你的意思是你只想要不存在一行不同的具有相同總數的ItemCode的行嗎? – Aleksej

+0

@Aleksej嗨阿列克謝謝謝你真的幫助我。我想要的只是獲得項目代碼'A'和'B'中不具有相同'Total'的所有項目名稱,但是如果它們在相同的項目代碼中並且具有相同的總數,我希望它們包括在內。 –

+0

你只想要對A和B或每對如(A,C)(B,C)等 –

回答

1

假設你需要爲不與同Total存在的不同itemCode另一行的行,並假設ItemCode始終不爲空,一個簡單的解決方案可以是這樣的:

with test(ItemCode, ItemName, Total) as 
(
    select 'A', 'name1', 5 from dual union all 
    select 'A', 'name1', 5 from dual union all 
    select 'A', 'name2', 10 from dual union all 
    select 'B', 'name1', 10 from dual union all 
    select 'B', 'name2', 25 from dual union all 
    select 'B', 'name1', 30 from dual union all 
    select 'C', 'name2', 5 from dual union all 
    select 'C', 'name1', 30 from dual union all 
    select 'C', 'name1', 20 from dual 
) 
select * 
from test t1 
where ItemCode in ('A', 'B') 
    and not exists (
        select 1 
        from test t2 
        where t1.total = t2.total 
        and t1.itemCode != t2.itemCode 
        and ItemCode in ('A', 'B') 
       ) 

以下是更快,但不太可讀:

select ItemCode, ItemName, Total 
from (
     select ItemCode, ItemName, Total, count(distinct ItemCode) over (partition by Total) as itemCount 
     from test 
     where ItemCode in ('A', 'B') 
    ) 
where itemCount = 1 
+0

這實際上工作!感謝男人@Aleksej 5豎起大拇指! –

1

嘗試此查詢:

select i.* 
from my_table i 
where i.ItemCode in ('A','B') 
and (select count(*) from my_table t where t.ItemCode in ('A','B') 
and t.ItemCode != i.ItemCode and t.total = i.total) = 0 
1
SELECT A.* FROM (SELECT * FROM MYTABLE WHERE ITEMCODE='A')A 
     LEFT JOIN (SELECT * FROM MYTABLE WHERE ITEMCODE='B')B ON 
    A.TOTAL=B.TOTAL 
WHERE B.ITEMCODE IS NULL 

UNION 

SELECT B.* FROM (SELECT * FROM MYTABLE WHERE ITEMCODE='B')B 
     LEFT JOIN (SELECT * FROM MYTABLE WHERE ITEMCODE='A')A ON 
    B.TOTAL=A.TOTAL 
WHERE A.ITEMCODE IS NULL