【问题标题】:How to select count of combination of values in one column which match single value of other column?如何选择一列中与另一列的单个值匹配的值组合计数?
【发布时间】:2017-02-19 16:29:52
【问题描述】:

我的数据如下:

表是:order_details(order_id int not null,prod_id int not null)

Order_id Prod_id
1              1
1              2
2             3
3             4
4             1
4             2
4             7

我需要查找订单中一起销售的两种或多种产品的组合。
对于此数据,这将是产品 1 和 2,因为它们在单个订单中出现两次。 我需要大多数订单一起出现的产品以及它们一起出现的订单数量。

我正在使用这个查询:

select distinct od1.prod_id,od2.prod_id from order_details od1 join order_details od2 on od1.order_id=od2.order_id  where od1.prod_id!= od2.prod_id limit 10;

这仅适用于 2 种产品的组合,不提供计数。

这可以做得更好吗?

谢谢!

【问题讨论】:

标签: mysql sql


【解决方案1】:
ariaDB [sandbox]> drop table if exists t;
Query OK, 0 rows affected (0.10 sec)

MariaDB [sandbox]> create table t (Order_id int,Prod_id int);
Query OK, 0 rows affected (0.19 sec)

MariaDB [sandbox]> insert into t values
    -> (1 ,             1),
    -> (1 ,             2),
    -> (2 ,             3),
    -> (3 ,             4),
    -> (4 ,             1),
    -> (4 ,             2),
    -> (4 ,             7),
    -> (5 ,             1),
    -> (5 ,             2),
    -> (6 ,             1),
    -> (6 ,             2),
    -> (6 ,             7),
    -> (7 ,             1),
    -> (7 ,             2),
    -> (7 ,             7),
    -> (8 ,   7),
    -> (8 ,  2)
    -> ;
Query OK, 17 rows affected (0.07 sec)
Records: 17  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select s.prodmix,count(*) Obs
    -> from
    -> (
    -> select order_id,
    -> group_concat(prod_id order by prod_id asc) prodmix, count(*) as obs
    -> from t
    -> group by order_id
    -> having count(*) > 1
    -> ) s
    -> group by prodmix
    -> order by obs desc limit 2;
+---------+-----+
| prodmix | Obs |
+---------+-----+
| 1,2,7   |   3 |
| 1,2     |   2 |
+---------+-----+
2 rows in set (0.04 sec)

【讨论】:

  • 谢谢。这就是我使用的: SELECT s.prodmix, count(s.prodmix) Obs FROM (SELECT order_id, group_concat(prod_id ORDER BY prod_id ASC) prodmix, count() AS obs FROM order_details GROUP BY order_id HAVING count() > 1) s GROUP BY prodmix ORDER BY obs DESC LIMIT 2;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多