现在的位置: 首页 > 综合 > 正文

一则SQL问题

2013年04月16日 ⁄ 综合 ⁄ 共 856字 ⁄ 字号 评论关闭

 f1    f2    f3
 ---------------------
 001    01    100
 002    01    200
 001    02    300
 002    02    400
 003    01    500
 004    02    600

若想显示为以下格式,应如果写 SQL语句?

 f1    f2    f3
 ---------------------
 001    01    100 
 001    02    300 
 001    合计    400 
 002    01    200 
 002    02    400 
 002    合计    600 
 003    01    500 
 003    合计    500 
 004    02    600 
 004    合计    600 
===============================================================================
Create table test
(
[ID] bigint Identity(1,1) primary key,
f1 varchar(50),
f2 varchar(50),
f3 int
)

drop table test

select * from test

insert into test values('001','01',100)
insert into test values('002','01',200)

insert into test values('001','02',300)
insert into test values('002','02',400)
insert into test values('003','01',500)
insert into test values('004','02',600)

select f1,'合计' as f2, sum(f3) as f3 from test group by f1
union
select f1,f2,f3 from test

抱歉!评论已关闭.