如何检索具有共同值的id并将它们一起显示?

时间:2015-10-15 18:15:33

标签: mysql

我是SQL的初学者。我有一个问题,我必须检索有4个或更多普通消费者的生产者ID。我想要显示  制片人Id与计数一起。例如,

我的示例数据库: Sample database - 我的示例数据库

样本输出应为a和b,因为它们共同提供4个部分(21,22,23,24)。

我想,我应该使用groupconcat并拥有权利吗?

Sample output

3 个答案:

答案 0 :(得分:0)

我想这会有所帮助:

SELECT GROUP_CONCAT(cusomer_id) FROM table GROUP BY pro_id HAVING COUNT(pro_id)>4

当你想根据聚合函数的结果(例如SUM和COUNT)过滤行时,HAVING是一个很好的方法。
“GROUP_CONCAT”将确保您将所有4个结果合并为一列

答案 1 :(得分:0)

SELECT `producer_id`, COUNT(`consumer_id`) AS cnt
FROM orders
GROUP BY `consumer_id`
HAVING COUNT(*) > 4

应该这样做。

更新,以获得每个制作人的消费者数量:

SELECT `producer_id`, COUNT(`consumer_id`) AS cnt
FROM orders
GROUP BY `producer_id`
HAVING COUNT(`consumer_id`) > 4

然后inner join获得您想要的结果:

SELECT tt1.producer_id, tt2.count
from (SELECT COUNT(consumer_id) as count, producer_id from ORDERS GROUP  BY producer_id HAVING COUNT(`consumer_id`) > 4) tt1
  INNER JOIN (SELECT COUNT(consumer_id) as count, producer_id from ORERS GROUP BY producer_id HAVING COUNT(`consumer_id`) > 4) tt2
     on tt1.producer_id = tt2.producer_id
WHERE tt1.count = tt2.count

测试并处理您的样本数据。

答案 2 :(得分:0)

create table t (p varchar(1), c int);
insert into t values('a',21);
insert into t values('a',22);
insert into t values('a',23);
insert into t values('a',24);
insert into t values('b',21);
insert into t values('b',22);
insert into t values('b',23);
insert into t values('b',24);
insert into t values('c',21);
insert into t values('c',22);
insert into t values('c',24);
insert into t values('d',22);
insert into t values('d',23);
insert into t values('d',25);
insert into t values('d',26);

// Get all the producers with at least 4 consumers,
// enumerate the consumers.
select p,
       group_concat(c order by c) g,
       count(*) c
from   t
group by p having count(*) >= 4;

+------+-------------+---+
| p    | g           | c |
+------+-------------+---+
| a    | 21,22,23,24 | 4 |
| b    | 21,22,23,24 | 4 |
| d    | 22,23,25,26 | 4 |
+------+-------------+---+

// Find common producers.
select group_concat(p) as producer,
       g as "group",
       c as count from(
  select p,
         group_concat(c order by c) g,
         count(*) c
  from   t
  group by p having count(*) >= 4
) t2 group by g having count(*) > 1;

+----------+-------------+-------+
| producer | group       | count |
+----------+-------------+-------+
| a,b      | 21,22,23,24 |     4 |
+----------+-------------+-------+