如何将多行数据分成不同列名的1行?

时间:2016-08-10 08:36:42

标签: sql sql-server sql-server-2008

我写了以下查询:

select user_id, id ,value 
from users us 
left join masterdata md 
    on md.id = us.id
left join masterdatatemp mdt 
    on mdt.id = us.id
where id = 6 and value = 1
   or id = 6 and value = 0 
order by id

以上查询返回:

User_Id ID VALUE
6       55  1
6       55  0
6       84  0
6       84  1

但我希望输出如下:

 User_Id    ID VALUE1  VALUE2
    6       55  1       0
    6       84  0       1

如何将多行转换为具有不同列名的单列?

1 个答案:

答案 0 :(得分:0)

我尝试如下,请根据您的要求修改

declare @user table(Userid varchar(max),ID int,value int)
insert into @user values (6,55,1)
insert into @user values (6,55,0)
insert into @user values (6,84,0)
insert into @user values (6,84,1)
select * from @user

declare @val varchar(max),@user_id varchar(max),@VAL1 INT ,@VAL2 INT
declare @values table(val int,id int identity(1,1))
declare @new_table table (Userid varchar(max),ID int,Value1 int,Value2 int)

declare c cursor for 
select distinct id,Userid from @user
open c
fetch next from c into @val,@user_id
while @@FETCH_STATUS=0
begin
    insert into @values select value from @user where id= @val

    SET @VAL1=(select top 1 val from @values)
    SET @VAL2=(select val from @values where id not in (select top 1 id from @values))
    insert into @new_table values (@user_id,@val,@VAL1,@VAL2)
    delete from @values
    fetch next from c into @val,@user_id
end
close c
deallocate c
select * from @new_table