商品关联分析
SQL查询入门SQL
问题
找出经常一起购买的商品组合(购物篮分析)。
答题要点
WITH order_products AS (
SELECT order_id, product_id
FROM order_items
),
product_pairs AS (
SELECT
a.product_id AS product_a,
b.product_id AS product_b,
COUNT(DISTINCT a.order_id) AS co_purchase_count
FROM order_products a
JOIN order_products b
ON a.order_id = b.order_id
AND a.product_id < b.product_id
GROUP BY a.product_id, b.product_id
)
SELECT
p1.product_name AS product_a,
p2.product_name AS product_b,
pp.co_purchase_count,
ROUND(pp.co_purchase_count * 100.0 / (SELECT COUNT(DISTINCT order_id) FROM order_items), 2) AS support_pct
FROM product_pairs pp
JOIN products p1 ON pp.product_a = p1.product_id
JOIN products p2 ON pp.product_b = p2.product_id
ORDER BY co_purchase_count DESC
LIMIT 20;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题