Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUM of grouped COUNT in SQL Query

Tags:

sql

count

sum

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 'count', and a row 'SUM'

 Name     Count -------  ----- Alpha     1 Beta      3 Charlie   2 SUM       6 

How would I write a query to add SUM row below the table?

like image 324
nametal Avatar asked Oct 17 '12 04:10

nametal


People also ask

Can we use SUM and count together in SQL?

SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

What is the difference between SUM and count in SQL?

COUNT() is used to count the number of rows for a given condition. COUNT() works on numeric as well as non-numeric values. SUM() is used to calculate the total sum of all values in the specified numeric column.


1 Answers

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 
like image 200
Vishal Suthar Avatar answered Oct 06 '22 00:10

Vishal Suthar