[英]How can I select records which has same value?
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.我想要 select 客户,他选择了他们所有产品的笔记本电脑,所以这个案例我想要 select 凯文,因为他选择了笔记本电脑他的所有产品。 I dont want to select john because he selected laptop but also select telephone not all product of john laptop.我不想 select 约翰因为他选择了笔记本电脑而且 select 电话不是约翰笔记本电脑的所有产品。
How can I do this in tsql?我如何在 tsql 中执行此操作?
You can use conditional aggregation in the having clause您可以在 having 子句中使用条件聚合
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(*)
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这应该对你有帮助,它可能不是最终的答案,但它应该足以让你在某些边缘情况下弄明白
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.