Skip to content
Advertisement

SQL – Return “True” if a customer purchased product A, and “False” otherwise [closed]

I have a simple SQL table with a list of customer IDs, Invoices, Products they have purchased (Product A, Product B..), etc..

I need to write a query that returns two columns – one for the list of existing customers and another boolean column which says “True” if the customer purchased product A, and false otherwise.

How do I do that?

Advertisement

Answer

You can use aggregation:

select customerid,
       max(case when productid = 'A' then 1 else 0 end)
from a
group by customerid;

Note: This uses 1 for “true” and 0 for “false”. If you want strings, you can use:

select customerid,
       max(case when productid = 'A' then 'True' else 'False' end)
from a
group by customerid;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement