Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Get total in last row of MySql result

Tags:

sql

php

mysql

For example I have a table like this:

product | quantity | something
-------------------------------
 abc    |   5      |  2
 xzy    |   5      |  2
 asd    |   10     |  2

When I need all record I do like this and get 3 results:

select * from tableName 

But I want get a 4th row for total of quantity(50) and something(6). Is it possible in sql query or I have to loop my result to get total after query execution? I want to do this in query if possible.

like image 985
Awan Avatar asked Mar 08 '11 12:03

Awan


People also ask

How do I get the last row in MySQL?

To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1.

What is the query to fetch the last record from the table?

We can use the command FIRST() to extract the first entry of a particular column and LAST() to extract the last entry of a particular column in a Table.

How do I total in MySQL?

MySQL SUM() Function The SUM() function calculates the sum of a set of values.


2 Answers

You can use rollup to generate totals, but you have to change it to an aggregate function, like this:

SELECT product, sum(quantity), sum(something)
FROM tableName
GROUP BY product WITH ROLLUP
like image 185
Chris Strickland Avatar answered Oct 03 '22 20:10

Chris Strickland


(SELECT product, 
        quantity, 
        something 
 FROM   tablename) 
UNION 
(SELECT "all"          AS product, 
        SUM(quantity)  AS quantity, 
        SUM(something) AS something 
 FROM   tablename) 

This is working query. It will add a fourth row as desired at the end of your result

like image 35
DhruvPathak Avatar answered Oct 03 '22 20:10

DhruvPathak