首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

行转列(找了好久没找到结果)解决方法

2012-01-26 
行转列(找了好久没找到结果)有表如下:IDAmountStyleA1500重不良A1300中不良A1150轻不良B1300重不良B1200轻

行转列(找了好久没找到结果)
有表如下:

ID                       Amount                 Style
A1                       500                       重不良
A1                       300                       中不良
A1                       150                       轻不良
B1                       300                       重不良
B1                       200                       轻不良
B2                       120                       轻不良

转换后:

ID                     重不良             中不良               轻不良
A1                     500                   300                     150
B1                     300                   -                         200
B2                     -                       -                         120


测试表:

create   table   test([id]   varchar(4),   amount   int,   style   varchar(6))

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, '轻不良 ')

drop   table   test

帮忙!!谢谢

[解决办法]
select ID,
sum(case when Style= '重不良 ' then Amount else 0 end) 重不良,
sum(case when Style= '中不良 ' then Amount else 0 end) 中不良,
sum(case when Style= '轻不良 ' then Amount else 0 end) 轻不良
from test group by ID
[解决办法]

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)

--result
id 轻不良 中不良 重不良
---- ------------ ------------ ------------
A1 150 300 500
B1 200 - 300
B2 120 - -

热点排行
Bad Request.