SQL Query获取结果集最后一行中所有列值的总和以及行总和(group by)

时间:2013-11-19 02:55:55

标签: mysql sql sql-server sql-server-2008

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

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

3 个答案:

答案 0 :(得分:16)

您可以使用GROUP BYWITH 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.

答案 1 :(得分:3)

此查询将完成工作

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

第一列将以varchar的形式返回,因为这样您就可以混合使用整数(id)和文本TCS

答案 2 :(得分:1)

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