Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get the Sum of all column values in the last row of a resultset along with row sum (group by)

Can someone please help me to write a query to obtain the TCS and TRS?

ID  Jan Feb Mar TRS
1   4   5   6   15
2   5   5   5   15
3   1   1   1   3
TCS 10  11  12  

Both TCS (Total Column Sum) and TRS (Total Row Sum) are new column and row respectively which gives their.

like image 453
ary Avatar asked Nov 19 '13 02:11

ary


People also ask

How do you find the sum of all the values in a column in SQL?

The SUM() function returns the total sum of a numeric column.

How do I get the sum of values in a 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.

Can we use sum in order by in SQL?

Discussion: Use ORDER BY if you want to order rows according to a value returned by an aggregate function like SUM() . The ORDER BY operator is followed by the aggregate function (in our example, SUM() ). DESC is placed after this function to specify a descending sort order.

How do I get subtotals in SQL query?

In order to calculate a subtotal in SQL query, we can use the ROLLUP extension of the GROUP BY statement. The ROLLUP extension allows us to generate hierarchical subtotal rows according to its input columns and it also adds a grand total row to the result set.


2 Answers

You can use GROUP BY and WITH ROLLUP, like this:

SELECT
    id
,   SUM(jan) as jan
,   SUM(feb) as feb
,   SUM(mar) as mar
,   SUM(jan+feb+mar) as TRS
FROM test
GROUP BY id WITH ROLLUP

Live demo on sqlfiddle.

like image 88
Sergey Kalinichenko Avatar answered Oct 05 '22 05:10

Sergey Kalinichenko


This query will do the job

select cast(id as varchar(20)), Jan, Feb, Mar , Jan + Feb + Mar as TRS
from table1

union all

select 'TCS' as id, SUM(Jan) Jan, SUM(Feb) Feb, SUM(Mar) Mar, null as TRS
from table1

The first column will be returned as varchar as this way you have a mix of integers (id) and the text TCS.

like image 35
Szymon Avatar answered Oct 05 '22 04:10

Szymon