我需要一个SQL查询来查找哪些产品与同一订单中的其他产品一起购买。
我有这个表:
orderId | productId | A111 | 1 |
---|---|
A111 | 21 |
A111 | 12 |
A111 | 31日 |
A122 | 21 |
A122 | 43 |
A122 | 32 |
A122 | 1 |
澳大利亚 | 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对。