I have a table. This table includes customers and products. Sample data is is in below.
Customer Name | Product |
---|---|
John | laptop |
John | telephone |
John | laptop |
Kevin | laptop |
Kevin | laptop |
Kevin | laptop |
I want to select customer who chose all their products with a laptop so This case I want to select Kevin because he selected laptop his all products. I dont want to select john because he selected laptop but also select telephone not all product of john laptop.
How can I do this in tsql?
CodePudding user response:
You can use conditional aggregation in the having clause
SELECT [Customer Name]
FROM YourTable t
GROUP BY [Customer Name]
HAVING COUNT(CASE WHEN Product <> 'laptop' THEN 1 END) = 0
-- alternatively
HAVING COUNT(CASE WHEN Product = 'laptop' THEN 1 END) = COUNT(*)
CodePudding user response:
SELECT Name
FROM Customers
WHERE (SELECT Name FROM Customers WHERE Product = 'telephone') != Name
GROUP BY NAME;
This should help you, it might not be the final asnwer but it shall provide enough for you to figure it out in some edge cases