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

SQL query show customers who bought apples, but not potatoes

Not sure how to explain this..

I have a similar table, but i have simplified it with the following:

I have a table of goods shipped to different cusotmers. Some have bought apples only, others have bought apples and potates.

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

I want an SQL query to return only customers where "To be billed" = Yes AND the customer hasnt bought any vegetables.

So for example if the table looks like this:

Item Name Group To_be_billed CustomerNo.
2000 Apple Fruit Yes 1
2000 Apple Fruit No 2
2000 Apple Fruit No 3
2000 Apple Fruit Yes 4
2000 Apple Fruit Yes 5
4000 Potato Vegetable No 2
4000 Potato Vegetable No 4

I want the query to return:

Item Name Group To_be_billed CustomerNo.
2000 Apple Fruit Yes 1
2000 Apple Fruit Yes 5

The reason 4 has bought apples, and is to be billed, but the customer also bought Potatoes, so is to be ignored…

>Solution :

You can create a CTE to check for CustomerNo.s that you need to ignore, and then use not exists:

with bought_veg as
(
    select "CustomerNo."
    from tbl
    where tbl."Group" like 'Vegetable'
)
select tbl.*
from tbl
where not exists (select 1 from bought_veg where tbl."CustomerNo." = bought_veg."CustomerNo.")
    and tbl.To_be_billed = 'Yes'

Example without CTE:

select tbl.*
from tbl
where not exists (select "CustomerNo." from tbl t2 where tbl.[CustomerNo.] = t2.[CustomerNo.] and "Group" like 'Vegetable')
    and tbl.To_be_billed = 'Yes'
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