Using COUNT in GROUP_CONCAT

前端 未结 5 1790
执笔经年
执笔经年 2021-02-19 12:29

This is my table:

  id  | fk_company
-------------------
  1   |     2    
  2   |     2    
  3   |     2    
  4   |     4    
  5   |     4    
  6   |     11          


        
相关标签:
5条回答
  • 2021-02-19 12:31

    Just use count(id)

    SELECT id, COUNT(id) as total
    FROM `table` GROUP BY fk_company;
    
    0 讨论(0)
  • 2021-02-19 12:37

    You can also achieve that by counting the number of commas (or whatever's your separator) in the GROUP_CONCAT:

    SELECT (LENGTH(GROUP_CONCAT(DISTINCT fk_company))-LENGTH(REPLACE(GROUP_CONCAT(DISTINCT fk_company), ',', '')))
    FROM `table`
    GROUP BY fk_company
    
    0 讨论(0)
  • 2021-02-19 12:44
    select GROUP_CONCAT(counts) 
       from (
          select count(id) counts from
              table group by fk_company
       );
    
    0 讨论(0)
  • 2021-02-19 12:49

    You need to COUNT() with GROUP BY in an inner SELECT clause first and then apply GROUP_CONCAT();

    SELECT GROUP_CONCAT(cnt) cnt
    FROM (
        SELECT COUNT(*) cnt
        FROM table1
        GROUP BY fk_company
    ) q;
    

    Output:

    |   CNT   |
    -----------
    | 3,2,3,1 |
    

    Here is SQLFiddle demo.

    0 讨论(0)
  • 2021-02-19 12:55
    SELECT A,  
    GROUP_CONCAT(B SEPARATOR '/') AS 'Category',  
    GROUP_CONCAT(C SEPARATOR '/') AS 'ALIAS_NAME',COUNT('ALIAS_NAME') AS 'Count'  
    FROM carnews  
    ...  
    ...
    GROUP BY 1
    ORDER BY 4 DESC  
    

    This works well in my case.

    0 讨论(0)
提交回复
热议问题