在红移上创建先验项集



我的目标是使用 Apriori 算法从在 AWS Redshift 上创建的购买表中找出有趣的见解。购买表如下图所示。

-------------
ID | product
1    A
1    B
1    C
2    A
2    C

我能够计算乘积的频率并以低频率过滤这些观察结果。但是,我在 AWS Redshift 环境中创建项集的规则时遇到了困难。这就是我想要得到的:

------------------
itemset | count(*)
A,B       1
A,C       2
B,C       1

购买表中有 1000 多种产品,因此我想学习如何编写有效且高效的查询来解决此问题。谢谢。

使用自连接:

select t1.product, t2.product, count(*)
from t t1 join
t t2
on t1.id = t2.id and t1.product < t2.product
group by t1.product, t2.product;

这会将项目集放在两列中。 您也可以将它们连接在一起:

select t1.product || ',' || t2.product, count(*)
from t t1 join
t t2
on t1.id = t2.id and t1.product < t2.product
group by t1.product, t2.product
order by t1.product || ',' || t2.product;

这是一个SQL小提琴,说明了代码的工作原理。

最新更新