You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SELECT customer_id, group_concat(product_key) AS product_key FROM Customer GROUP BY customer_id;
分组之后通过 having 过滤掉购买商品数量不等于全部商品数量的用户:
第一个 count 需要使用 distinct 去重,可能会出现同一个用户买了多件商品
第二个 count 不需要去重,因为商品不会重复 COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);
SELECT
customer_id
FROM
Customer
GROUP BY
customer_id
HAVINGcount( DISTINCT product_key ) = ( SELECTcount(*) FROM Product );
方法二
先通过 group by coustomer_id 分组
分组之后,可以使用 group_concat 函数将商品编号拼接成字符串
group_concat( DISTINCT product_key ORDER BY product_key ):将 Customer 表中每个用户购买的商品编号拼接成字符串
SELECT group_concat( product_key ORDER BY product_key ) FROM Product:将 Product 表中的商品编号拼接成字符串
然后比较两个字符串是否相等
SELECT
customer_id
FROM
Customer
GROUP BY
customer_id
HAVING
group_concat( DISTINCT product_key ORDER BY product_key ) = ( SELECT group_concat( product_key ORDER BY product_key ) FROM Product )
The text was updated successfully, but these errors were encountered:
题目
题目链接:买下所有产品的客户
编写解决方案,报告 Customer 表中购买了 Product 表中所有产品的客户的 id。
返回结果表 无顺序要求。
返回结果格式如下所示。
本题考察了 2 个知识点:
SQL
方法一
SELECT COUNT(*) FROM product;
SELECT customer_id, group_concat(product_key) AS product_key FROM Customer GROUP BY customer_id;
having
过滤掉购买商品数量不等于全部商品数量的用户:count
需要使用distinct
去重,可能会出现同一个用户买了多件商品count
不需要去重,因为商品不会重复COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);
方法二
group by coustomer_id
分组group_concat
函数将商品编号拼接成字符串group_concat( DISTINCT product_key ORDER BY product_key )
:将Customer
表中每个用户购买的商品编号拼接成字符串SELECT group_concat( product_key ORDER BY product_key ) FROM Product
:将Product
表中的商品编号拼接成字符串The text was updated successfully, but these errors were encountered: