有这样两个表:
table_a:
id name val
1 aaa 30
2 aaa 40
3 aaa 50
1 bbb 35
2 bbb 45
3 bbb 55
table_b:
name val1 val2 val3
aaa 30 40 50
bbb 35 45 55
请用一个SQL语句实现table_a到table_b的转化。
1
create table tb(id int, name varchar(10), val int)
2
insert into tb values(1 , 'aaa' , 30 )
3
insert into tb values(2 , 'aaa' , 40 )
4
insert into tb values(3 , 'aaa' , 50 )
5
insert into tb values(1 , 'bbb' , 35 )
6
insert into tb values(2 , 'bbb' , 45 )
7
insert into tb values(3 , 'bbb' , 55 )
8
go
9
10
--sql 2000静态,指ID只有1,2,3
11
select name ,
12
sum(case id when 1 then val else 0 end) [val1],
13
sum(case id when 2 then val else 0 end) [val2],
14
sum(case id when 3 then val else 0 end) [val3]
15
from tb
16
group by name
17
/**//*
18
name val1 val2 val3
19
---------- ----------- ----------- -----------
20
aaa 30 40 50
21
bbb 35 45 55
22
23
(所影响的行数为 2 行)
24
*/
25
26
--sql 2000动态,指ID不确定
27
declare @sql varchar(8000)
28
set @sql = 'select name '
29
select @sql = @sql + ' , sum(case id when ''' + cast(id as varchar) + ''' then val else 0 end) [val' + cast(id as varchar) + ']'
30
from (select distinct id from tb) as a
31
set @sql = @sql + ' from tb group by name'
32
exec(@sql)
33
/**//*
34
name val1 val2 val3
35
---------- ----------- ----------- -----------
36
aaa 30 40 50
37
bbb 35 45 55
38
*/
39
40
41
drop table tb
42
posted on 2009-08-17 10:14
absolute 阅读(417)
评论(0) 编辑 收藏 所属分类:
DataBase