简体   繁体   中英

Where clause with multiple conditions in SQL DB2

Col1    Col2        Col3

ABC     Product     Digital
ABC     SubProduct  XF
BCD     Product     Non-Digital
BCD     SubProduct  <White Space>
CDE     Product     Digital
CDE     SubProduct  Null
DEF     Product     Non-Digital
DEF     SubProduct  FR

Desired Output:

Col1    Product         SubProduct

ABC     Digital         XF
DEF     Non-Digital     FR

Query:

SELECT * 
FROM TABLE
WHERE (Col2 IN ('Product','SubProduct') AND NOT Col3 LIKE '')

Any help is greatly appreciated

Try this:

WITH TAB (Col1, Col2, Col3) AS
(
VALUES
  ('ABC', 'Product', 'Digital')
, ('ABC', 'SubProduct', 'XF')
, ('BCD', 'Product', 'Non-Digital')
, ('BCD', 'SubProduct', ' ')
, ('CDE', 'Product', 'Digital')
, ('CDE', 'SubProduct', Null)
, ('DEF', 'Product', 'Non-Digital')
, ('DEF', 'SubProduct', 'FR')
)
SELECT A.Col1, A.Col3 AS Product, B.Col3 AS SubProduct
FROM TAB A
JOIN TAB B ON B.Col1 = A.Col1 AND B.Col2 = 'SubProduct'
WHERE A.Col2 = 'Product' AND NULLIF(B.Col3, '') IS NOT NULL;

|COL1|PRODUCT    |SUBPRODUCT |
|----|-----------|-----------|
|ABC |Digital    |XF         |
|DEF |Non-Digital|FR         |

dbfiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM