日期:2014-05-16  浏览次数:20745 次

SQL多条数据转换为一条的问题
 CREATE TABLE [dbo].[T](
[VAX01] [int] NULL,
[VAT01] [INT] NULL,
[ACE01] [int] NULL,
[BCE03] [nchar](10) NULL,


INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45346','1642103','21','张燕')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45347','1642103','22','王正')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45348','1642103','23','陈方')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45349','1642103','02','周梅')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45350','1642103','01','李强')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45351','1642103','11','吕布')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45352','1642106','11','刘伟')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45353','1642106','22','王正')
INSERT INTO T (VAX01,VAT01,ACE01,BCE03)VALUES('45354','1642106','23','周青')
--------------------------------------------------------------------------------------------------------------------------------------
目前只能查出来这样的结果,郁闷:
select VAT01,(case when ACE01=21 then BCE03 else '' end) as A,
(case when ACE01=23 then BCE03 else '' end) as B,
(case when ACE01=22 then BCE03 else '' end) as C
 from t group by VAT01,ACE01,BCE03,VAT01
-------------------------------------------------------------------------------------------------
1642103
1642103
1642103
1642103 张燕        
1642103 王正        
1642103 陈方        
1642106
1642106 王正        
1642106 周青        
 
------------------------------------------------------------------------------------------------------------------
 想要查询出来只有一行结果,如下所示:
 
 VAT01           A         B          C
 -------------------------------------------
 1642103   张燕   陈方    王正
 1642106              周青    王正 
 ---------------------------------------

求各位大能各显神通啊!!!!!!!!
------解决方案--------------------
create table T(vax01 int null ,vat01 int null,ace01 int null ,bce03 nchar(10) null)
insert T
select 45346,1642103,21,'张燕' union all
select 45347,1642103,22,'王正'union all
select 45348,1642103,23,'陈方' union all
select 45349,1642103,02,'周梅'union all
select 45350,1642103,01,'李强' union all
select 45351,1642103,11,'吕布'union all
select 45352,1642106,11,'刘伟' union all
select 45353,1642106,22,'王正'union all
select 45354,1642106,23,'周青'

select vat01 ,
max(case when ace01='21' then bce03 end) as A,
max(case when ace01='23' then bce03 end) as B,
max(case when ace01='22' then bce03 end) as C
from t
group by vat01