2017-07-31 42 views
-3

我的表有不同的價值觀選擇的ID看起來如下:橫跨兩列

EAN | Country | Status 
1 | Germany | A 
1 | France | B 
1 | Spain | A 
2 | Germany | A 
2 | France | A 
2 | Spain | A 

我需要每一個ID,其狀態爲「A」至少在一個國家,但不是在至少一種其他。

在此示例中,結果應該包含ID 1,因爲它在德國和西班牙的狀態爲「A」,但在法國沒有。

+1

請給DBMS添加標籤,並編輯您的Q以包含您已經嘗試過的內容。 – JohnHC

回答

1

嘗試自聯接

select distinct main.EAN 
    from [table] main 
    join [table] sub 
    on main.EAN = sub.EAN and 
     main.Country <> sub.Country and 
     main.Status <> sub.Status 

[table]必須與您的實際表的名稱所取代。這應該會給你想要的結果。

+0

真棒,簡單但功能...非常感謝! – chack

+0

我剛加了'distinct'關鍵詞來避免重複的結果。 –

0

使用子查詢,你可以做到以下幾點:

select 
    EAN 
from 
    (
    select 
     EAN, 
     sum(case when Status = "A" then 1 else 0 end) statusA, 
     sum(case when Status <> "A" then 1 else 0 end) statusOther 
    from 
     statuses 
    group by 
     EAN 
) summary 
where 
    summary.statusA > 0 and 
    summary.statusOther > 0 

看到一個例子here