有人可以帮我写一个查询来获取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(总行总和)分别是新的列和行,给出了它们。
答案 0 :(得分:16)
您可以使用GROUP BY
和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
答案 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