Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select subset of data from multiple columns in SQL?

Assume I have a table such as following and I would like to select customers who purchased more than 1 item.

customer item1 item2 item3 item4
1 10 NULL NULL NULL
2 5 11 NULL NULL
3 7 NULL 9 NULL
4 NULL NULL 2 NULL
5 7 13 9 NULL

My final output should be something like

customer item1 item2 item3 item4
2 5 11 NULL NULL
3 7 NULL 9 NULL
5 7 13 9 NULL

My code is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT  
       customer
      ,item1
      ,item2
      ,item3
       item4
FROM StoreData
WHERE item1 IS NOT NULL OR 
      item2 IS NOT NULL OR
      item3 IS NOT NULL OR
      item4 IS NOT NULL

But this seems to be incorrect? Any suggestions? Many Thanks

>Solution :

Try something like this:

WHERE 
(
 (CASE WHEN item1 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item2 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item3 IS NOT NULL THEN 1 ELSE 0 END) 
+(CASE WHEN item4 IS NOT NULL THEN 1 ELSE 0 END) 
) > 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading