2011-06-09 72 views
0

這可能是很難的標題來形容,這裏有一個樣本數據:在SQL中,如何匹配特定行上的特定列?

id pub_type general_suppl book_suppl catalogue_suppl magazine_suppl 
1 book  10    10   0    0 
2 book  11    11   0    0 
3 catalogue 10    0   10    0 
4 magazine 9    0   0    9 
5 other  10    0   0    0 
6 magazine 8    0   0    10 

每個項目的是一個特定出版物類型與一般的供應商和出版的一類供應商。 other商品只有general_suppl。如果我想獲得供應商價值10的所有項目,以下條件必須滿足:

if pub_type == 'book' 
    match on book_suppl == 10 
elif pub_type == 'catalogue' 
    match on catalogue_suppl == 10 
elif pub_type == 'magazine' 
    match on magazine_suppl == 10 
else 
    match on general_suppl == 10 

正如你可以在上面看到,如果pub_type落在book,catalogue,magazine,我忽略列general_suppl

上的供應商值10預期的輸出將是:

id pub_type general_suppl book_suppl catalogue_suppl magazine_suppl 
1 book  10    10   0    0 
3 catalogue 10    0   10    0 
5 other  10    0   0    0 
6 magazine 8    0   0    10 

我可以通過檢索所有的行實現上述和在代碼級別執行濾波。是否有單一的SQL方法來獲得上述結果?數據庫設計和數據超出了我的控制範圍,所以我不能重新設計數據庫,而必須使用上述表結構。

+0

爲什麼要爲Booksupplier,MagazineSupplier等設置單獨的欄目?如果每個發佈類型只能擁有該特定發佈類型的供應商,那麼這看起來很複雜並且沒有什麼價值。在您的示例數據中,沒有行有兩列填充了不同的供應商ID。那麼爲什麼不只是有一個「供應商」欄? – 2011-06-09 20:16:44

+0

@Charles Bretana他已經表示設計超出了他的控制範圍。希望在他接受dpmattingly的回答後,他可以將設計師從一座橋樑中解放出來。 :-) – MarkD 2011-06-09 20:20:48

+0

這是我最初的觀察,我同意這是錯誤的數據庫設計,但我必須使用這種表和數據。 – 2011-06-09 20:21:46

回答

5

這是醜陋的,但你可以把這個邏輯放入CASE結構中。

SELECT * 
FROM table 
WHERE 10 = CASE WHEN pub_type = 'book' THEN book_suppl 
       WHEN pub_type = 'catalogue' THEN catalogue_suppl 
       WHEN pub_type = 'magazine' THEN magazine_suppl 
       ELSE general_suppl END 
0

and來救援!

select * 
from table 
where (pub_type='book' and book_suppl=10) 
    or (pub_type='catalogue' and catalogue_suppl=10) 
    or (pub_type='magazine' and magazine_suppl=10) 
    or (pub_type not in ('book','catalogue','magazine') and general_suppl=10) 
相關問題