【问题标题】:Count combinations of rows in a group with SQL使用 SQL 计算组中的行组合
【发布时间】:2019-12-27 19:07:08
【问题描述】:

我有一张包含订单及其产品的表格:

+-------+---------+
| Order | Product |
+-------+---------+
| A     |       1 |
| A     |       2 |
| A     |       2 |
| A     |       3 |
| B     |       1 |
| B     |       3 |
| B     |       4 |
| C     |       1 |
| C     |       3 |
+-------+---------+

当两个产品一起订购以识别流行产品组合时,我想计算出现次数:

+---------------+----------------+-------+
| First product | Second product | Count |
+---------------+----------------+-------+
|             1 |              2 |     1 |
|             1 |              3 |     3 |
|             1 |              4 |     1 |
|             2 |              3 |     1 |
|             2 |              4 |     0 |
|             3 |              4 |     0 |
+---------------+----------------+-------+

【问题讨论】:

    标签: sql statistics combinations


    【解决方案1】:

    使用自加入和分组方式:

    select op1.product, op2.product, count(*)
    from orderproduct op1 join
         orderprodut op2
         on op1.order = op2.order and
            op1.product < op2.product
    group by op1.product, op2.product
    order by count(*) desc;
    

    如果您想要最流行的组合,我看不出需要哪些与0 的组合,因此不包括它们。

    以上计算所有组合(订单中的倍数)。如果要统计订单,请使用count(distinct)

    select op1.product, op2.product, count(distinct op1.order)
    from orderproduct op1 join
         orderprodut op2
         on op1.order = op2.order and
            op1.product < op2.product
    group by op1.product, op2.product
    order by count(*) desc;
    

    或将select distinct 与子查询一起使用。哪个更快取决于订单中重复产品的数量。

    【讨论】:

    • 您可能希望在 FROM op1 和 FROM op2 中使用 SELECT DISTINCT (Order,Product) 以避免在一个订单中计算两次组合。
    • 谢谢!这正是我需要的答案。
    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多