如何将列的总和作为包含列数据的新行

时间:2015-08-26 04:21:28

标签: sql

有一个包含四列的表格:

SrNo Descript item1 item2 
1   | AA     | 45  | 25
2   | BB     | 25  | 51
3   | CC     | 41  | 22

我希望得到这样的结果:

SrNo| Descript| item1 |item2| totalitems
1   | AA      | 45    | 25  |  70
2   | BB      | 25    | 51  |  76
3   | CC      | 41    | 22  |  63
4   | Total   | 111   | 98  | 209

3 个答案:

答案 0 :(得分:2)

像这样的东西

select SrNo, Descript, item1, item2, item1+item2 as totalitems
from yourtable
Union all
select max(SrNo)+1, 'Total', sum(item1), sum(item2), sum(item1)+sum(item2) as totalitems
from yourtable

注意:如果item1item2的数据类型为varchar,那么您可能必须castint在addititon之前

答案 1 :(得分:1)

尝试;

select 
  SrNo, Descript, item1, item2, 
  item1+item2 as totalitems
from tbl
ORDER BY SrNo

union all

select  
  max(SrNo) + 1, 'Total', sum(item1), sum(item2), 
  sum(item1+item2) as totalitems
from tbl

答案 2 :(得分:0)

试试这样:

drop table #t
create table #t(SrNo int, Descript varchar(10),item1 int,item2 int)
insert into #t values( 
1,'AA',45,25),
(2,'BB',25,51),
(3,'CC',41,22)


select  SrNo,Descript,item1,item2,item1+item2 as total into t6
from #t

select * from t6
union all

select 4,'Total',sum(item1),sum(item2),sum(total) from t6

fiddle demo