Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

showing sum in last row of table using mysql

I have the following Table elements how do i run a query that reproduce the table but hav an extra row at the bottom showing the sum of col2

Col1  | col2  
---------------
Water |  22  
water |   3      
water |   5      
Air   |  10      
Earth |   3       
Air   |   5    
like image 810
dames Avatar asked Apr 06 '12 01:04

dames


People also ask

How can we view last record added to a table?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.

How do I show the sum of each row in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; The SELECT statement in SQL tells the computer to get data from the table.

How do I find the last value in a table in SQL?

We could use LAST_VALUE() in SQL Server to find the last value from any table. LAST_VALUE() function used in SQL server is a type of window function that results the last value in an ordered partition of the given data set.


1 Answers

I don't know why you want that but give this a try:

SELECT Col1, Col2 FROM tableName
UNION
SELECT 'SUM' as Col1, SUM(Col2) Col2 FROM tableName
like image 56
John Woo Avatar answered Oct 02 '22 18:10

John Woo