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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With