MySQL SQL 查询以获取结果集最后一行中所有列值的总和以及行总和(分组依据)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20062270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:28:35  来源:igfitidea点击:

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

mysqlsqlsql-serversql-server-2008

提问by ary

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

有人可以帮我写一个查询来获取 TCS 和 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.

TCS(总列总和)和 TRS(总行总和)分别是新的列和行,它们给出了它们。

回答by dasblinkenlight

You can use GROUP BYand WITH ROLLUP, like this:

您可以使用GROUP BYand WITH ROLLUP,如下所示:

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.

sqlfiddle 上的现场演示。

回答by Szymon

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 varcharas this way you have a mix of integers (id) and the text TCS.

第一列将返回,varchar因为这样您将混合整数 (id) 和 text TCS

回答by Jonnas Macaraeg

select Sum(Jan + Feb + Mar) As TRS

选择 Sum(Jan + Feb + Mar) 作为 TRS