Reputation: 119
I want to find customers who have only bought fruit in their purchase. My data looks like this:
ID purchase_date product
22212 2021-06-03 Fruit
111999 2021-06-03 Fruit
111999 2021-06-03 Chocolate
56727 2019-05-03 Bread
30726 2019-05-03 Fruit
30726 2019-05-03 Chocolate
53899 2019-05-03 Fruit
I want this:
ID purchase_date
22212 2021-06-03
53899 2019-05-03
Thinking I need a where clause, grouped by ID and Purchase_date?
Upvotes: 1
Views: 116
Reputation: 333
You can use correlated queries as well.
SELECT DISTINCT T1.ID, T1.purchase_date
FROM <TableName> T1
WHERE T1.product = 'Fruit'
AND NOT EXISTS ( SELECT 1
FROM <TableName> T2
WHERE Product <> 'Fruit'
AND T1.ID = T2.ID
)
Upvotes: 0
Reputation: 99
Select Id, purchase_date
From your_table_name
Where lower(product) = 'fruit'
Upvotes: 1
Reputation: 46219
You can try to use Having
with condition aggregate function to write the logic.
COUNT
with fruit count will be greater than 1 )Fruit
Query 1:
SELECT ID,purchase_date
FROM T
GROUP BY ID,purchase_date
HAVING
COUNT(CASE WHEN product='Fruit' THEN 1 END) > 0
AND
COUNT(CASE WHEN product<>'Fruit' THEN 1 END) = 0
| ID | purchase_date |
|-------|---------------|
| 53899 | 2019-05-03 |
| 22212 | 2021-06-03 |
Upvotes: 3