一则SQL问题

 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

posted @ 2007-03-02 15:11  RobotTech  阅读(171)  评论(0编辑  收藏  举报