SUM of grouped COUNT in SQL Query

前端 未结 17 1718
夕颜
夕颜 2020-12-04 08:19

I have a table with 2 fields:

ID  Name
--  -------
1   Alpha
2   Beta
3   Beta
4   Beta
5   Charlie
6   Charlie

I want to group them by name, with \'co

相关标签:
17条回答
  • 2020-12-04 08:37
    SELECT name, COUNT(name) AS count
    FROM table
    GROUP BY name
    
    UNION ALL
    
    SELECT 'SUM' name, COUNT(name)
    FROM table
    

    OUTPUT:

    name                                               count
    -------------------------------------------------- -----------
    alpha                                              1
    beta                                               3
    Charlie                                            2
    SUM                                                6
    
    0 讨论(0)
  • 2020-12-04 08:40

    You can try group by on name and count the ids in that group.

    SELECT name, count(id) as COUNT FROM table group by name
    
    0 讨论(0)
  • 2020-12-04 08:41

    Please run as below :

    Select sum(count) 
      from (select Name, 
                   count(Name) as Count 
              from YourTable
          group by Name);  -- 6
    
    0 讨论(0)
  • 2020-12-04 08:44

    Use it as

    select Name, count(Name) as Count from YourTable
    group by Name
    union 
    Select 'SUM' , COUNT(Name) from YourTable
    
    0 讨论(0)
  • 2020-12-04 08:47
    SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
    FROM Table GROUP BY name
    
    0 讨论(0)
  • 2020-12-04 08:47

    I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries

    SYNTAX:

    select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;
    

    Example:

    select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;
    
    0 讨论(0)
提交回复
热议问题