今天做到leetcode上的一道题, 题目的意思大概就是去筛选出同时购买了A商品和B商品却没有购买C商品的客户。
Order表的字段信息如下:
Table: Orders
±--------------±--------+
| Column Name | Type |
±--------------±--------+
| order_id | int |
| customer_id | int |
| product_name | varchar |
±--------------±--------+
order_id is the primary key for this table.
customer_id is the id of the customer who bought the product “product_name”.
最直接的方法当然是通过3个in子查询,但是总觉得这个方法不够简洁,而且查询效率也不高。但想了好久也没想出其他方法。然后上网查了查,结果发现了一个自己之前完全没意识到的用法,就是sum函数的条件聚合。比如说购买A商品的客户就可以通过sum(product_name=‘A’)>0 来筛选得到,同理对于B和C。通过这种方法可以写出如下的SQL语句
select * from Customers where
customer_id in
(select customer_id from Orders
group by customer_id
having sum(product_name="A")>0 AND sum(product_name="B")>0 AND sum(product_name="C")=0);
当然不是说这个方法有多高效, 更多的应该是在写SQL时思路会更多一些。
好吧,希望对大家有帮助。