2014-01-22 36 views
0

以下查詢:MySQL的分組結果

SELECT COUNT(*) AS count, items.category, customers.sector 
FROM customers 
LEFT JOIN items ON items.customer_id = customers.id 
GROUP BY items.category, customers.sector 
ORDER BY customers.sector ASC 

給了我這樣的結果:

| count |   category  | sector | 
|-------|-----------------------|--------------| 
| 3 | A-Frames & Trolleys | Automotive | 
| 4 |  Suction Mounts | Automotive | 
| 1 |   Hand Cups  | Automotive | 
| 103 |  Glazing Tools | Construction | 
| 2 | A-Frames & Trolleys | Construction | 
| 2 |  Suction Mounts | Construction | 
|_______|_______________________|______________| 

我想部門欄是唯一的,以示與最大計數 例如類別:

| count |   category  | sector | 
|-------|-----------------------|--------------| 
| 4 |  Suction Mounts | Automotive | 
| 103 |  Glazing Tools | Construction | 
|_______|_______________________|______________| 

謝謝

+0

所以,你想要的'MAX(COUNT())'每個'sector'? – Kermit

+0

是的,這就是我所追求的 –

回答

2

我認爲這樣做最簡單的方法是substring_index()/group_concat()招:

select max(count) as `count`, 
     substring_index(group_concat(category order by count desc), ',', 1) as category, 
     sector 
from (SELECT COUNT(*) AS count, i.category, c.sector 
     FROM customers c LEFT JOIN 
      items i 
      ON i.customer_id = c.id 
     GROUP BY i.category, c.sector 
    ) t 
group by c.sector;