开发者

In SQL, how do I match specific columns on specific rows?

This might be hard to describe in the title, here's a sample data:

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

Each of the item is of a specific publication type with a general supplier and a supplier for the type of publication. other items only have a general_suppl. If I want to get all items on supplier value 10, the following conditions will have to be met:

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

As you can see above, if pub_type falls in book,catalogue,magazine, I ignore the column general_suppl.

The expected output on supplier value 10 will be:

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

I can achieve the above by retrieving all the rows and perform filtering at the code level. Is there a single SQL way to get the above results? The database design and data are be开发者_如何学Cyond my control, so I can't re-design the DB and will have to work with the above table structure.


It's ugly, but you can throw that logic into a CASE structure.

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


and to the rescue!

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜