SQL行转列
2007-02-26 15:38 清炒白菜 阅读(755) 评论(0) 编辑 收藏 举报
方法1:
方法2:
create table test([id] varchar(4), amount int, style varchar(20))
insert into test values('A1',500,'重不良')
insert into test values('A1',300,'中不良')
insert into test values('A1',150,'轻不良')
insert into test values('B1',300,'重不良')
insert into test values('B1',200,'轻不良')
insert into test values('B2',120,'轻不良')
declare @sql varchar(8000)
set @sql='select [id], '
select @sql=@sql+quotename(style)+'=max(case when style='+quotename(style, '''')+' then rtrim(amount) else ''-'' end),' from test group by style
select @sql=left(@sql, len(@sql)-1), @sql=@sql+' from test group by [id]'
exec(@sql)
insert into test values('A1',500,'重不良')
insert into test values('A1',300,'中不良')
insert into test values('A1',150,'轻不良')
insert into test values('B1',300,'重不良')
insert into test values('B1',200,'轻不良')
insert into test values('B2',120,'轻不良')
declare @sql varchar(8000)
set @sql='select [id], '
select @sql=@sql+quotename(style)+'=max(case when style='+quotename(style, '''')+' then rtrim(amount) else ''-'' end),' from test group by style
select @sql=left(@sql, len(@sql)-1), @sql=@sql+' from test group by [id]'
exec(@sql)
方法2:
create table T(名字 varchar(10), 科目 varchar(10), 分数 int)
insert T select '1', '语文', 90
union all select '1', '数学', 80
union all select '2', '语文', 90
union all select '2', '数学', 85
union all select '2', '外语', 70
declare @sql varchar(8000)
declare @sql2 varchar(1000)
set @sql=''
set @sql2='總分='
select @sql=@sql+quotename(科目)+'=isnull( max(case when 科目='+quotename(科目, '''')+' then 分数 end), 100),',
@sql2=@sql2+'tmp.'+科目+'+'
from T
group by 科目
select
@sql2=left(@sql2, len(@sql2)-1),
@sql=left(@sql, len(@sql)-1),
@sql='select tmp.*,'+@sql2+' from (select 名字,'+@sql,
@sql=@sql+' from T group by 名字) tmp'
exec(@sql)
insert T select '1', '语文', 90
union all select '1', '数学', 80
union all select '2', '语文', 90
union all select '2', '数学', 85
union all select '2', '外语', 70
declare @sql varchar(8000)
declare @sql2 varchar(1000)
set @sql=''
set @sql2='總分='
select @sql=@sql+quotename(科目)+'=isnull( max(case when 科目='+quotename(科目, '''')+' then 分数 end), 100),',
@sql2=@sql2+'tmp.'+科目+'+'
from T
group by 科目
select
@sql2=left(@sql2, len(@sql2)-1),
@sql=left(@sql, len(@sql)-1),
@sql='select tmp.*,'+@sql2+' from (select 名字,'+@sql,
@sql=@sql+' from T group by 名字) tmp'
exec(@sql)