SQL -一起购买的产品列表



我需要一个SQL查询来查找哪些产品与同一订单中的其他产品一起购买。

我有这个表:

tbody> <<tr>
orderId productId
A1111
A11121
A11112
A11131日
A12221
A12243
A12232
A1221
澳大利亚12
澳大利亚64
澳大利亚63
澳大利亚21
澳大利亚12

您可以使用自连接:

select distinct t1.productid, t2.productid
from t t1 join
t t2
on t1.orderid = t2.orderid
where t1.productid <> t2.productid;

如果你有一个产品表,你也可以这样表达:

select p1.productid, p2.productid
from products p1 cross join
products p2
where exists (select 1
from t t1 join
t t2
on t1.orderid = t2.orderid
where t1.productid = p1.productid and
t2.productid = p2.productid
);

试试这个:

SELECT a.productId AS item_1,
b.productId AS item_2,
COUNT(*) AS times_bought_together
FROM your_table_name a
JOIN your_table_name b
ON a.orderId = b.orderId
WHERE a.productId > b.productId 
GROUP BY a.productId, b.productId 
ORDER BY times_bought_together DESC

这还包括一个列,显示一起购买频率更高的商品的频率。

要小心,因为这可能包括对上的一些none。您可以添加更多代码来过滤NONE值,但在我的情况下,这是不必要的,因为我只需要前3对。

最新更新