日期:2014-05-18  浏览次数:20403 次

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

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( &#