2015-10-15 69 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 | 
+----------+-------------+-------+