2015-10-15 64 views
0

我是SQL的初学者。我有一个问题,在那里我必须检索有4个或更多普通消费者的生产者编号。我想显示 Producer Id和count。对于实施例,如何检索具有共同价值的ID并将它们一起显示?

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

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

我想,我应该使用groupconcat,并有正确的?

Sample output

+1

你可以发布你的表结构吗?提供的示例不明确。 –

+0

是的,只是添加了它的图片。我是新来的:| –

+0

如何找出哪些具有相同的ID。在图片中是最空的ids –

回答

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 

测试并在您的样本数据的工作。

+0

这样做看起来并不正确,因为它是按照'consumerID'列中的唯一值进行分组的,这将导致每个唯一的'consumerID'值产生一个包含6行的输出,因此它肯定不会生成预期的结果集 –

+0

感谢您的评论,但是,我希望它像a和b一样有4个共同点 –

+0

嗨,我尝试了更新后的答案,但它显示了个人数。 b-4 –

0

我想这会帮助:

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

HAVING是一个很好的方法,当你想基于聚合函数(如SUM和COUNT)的结果来筛选行。
“GROUP_CONCAT”将确保你得到所有4个结果组合在一列

+0

这看起来不正确,因为它根本没有考虑到consumerID。这将仅显示'a',因为它具有多于4个'consumerID'字段的值。 –

+0

是的,我没有得到任何输出兄弟:( –

+0

而我想输出作为组合,你可以在我的示例输出中看到a和b共同拥有4个 –

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 | 
+----------+-------------+-------+