【问题标题】:MySQL Group resultsMySQL 组结果
【发布时间】:2014-01-22 14:31:19
【问题描述】:

以下查询:

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 |
|_______|_______________________|______________|

谢谢

【问题讨论】:

  • 所以您想要每个sectorMAX(COUNT())
  • 是的,这就是我所追求的

标签: mysql count group-by distinct


【解决方案1】:

我认为最简单的方法是 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;

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 2019-02-15
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多