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.
To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1.
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.
MySQL SUM() Function The SUM() function calculates the sum of a set of values.
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
(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
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