日期:2014-05-19  浏览次数:20577 次

行转列
数据
a,a1
a,a2
b,b1
b,b2
变成
a,a1,a2
b,b1,b2

------解决方案--------------------
select a,min(col1) ,max(col2) from tb group by a
----

------解决方案--------------------
估计不是楼主想要的
create table test ( col1 char(10),col2 char(10))
go
insert into test
select 'a ', 'a1 '
union all
select 'a ', 'a2 '
union all
select 'b ', 'b1 '
union all
select 'b ', 'b2 '
go
--select * from test

select col1,min(col2) ,max(col2) from test group by col1

drop table test

------
col1
---------- ---------- ----------
a a1 a2
b b1 b2

(所影响的行数为 2 行)


------解决方案--------------------
create table test ( col1 char(10),col2 char(10))
go
insert into test
select 'a ', 'a1 '
union all
select 'a ', 'a2 '
union all
select 'b ', 'b1 '
union all
select 'b ', 'b2 '

create function test_f(@col1 varchar(2))
returns varchar(50)
as
begin
declare @s varchar(50)
select @s=isnull(@s+ ', ', ' ')+rtrim(col2) from test where col1=@col1
return @s
end

select distinct col1,col2=dbo.test_f(col1) from test

drop function test_f
drop table test
col1 col2
---------- --------------------------------------------------
a a1,a2
b b1,b2

(2 行受影响)


------解决方案--------------------
create table test(col1 varchar(2),col2 varchar(2))
insert into test
select 'a ', 'a1 '
union all
select 'a ', 'a2 '
union all
select 'a ', 'a3 '
union all
select 'b ', 'b1 '
union all
select 'b ', 'b2 '

declare @sql varchar(8000),@c int,@ct1 int
select top 1 @ct1=count(col2) from test group by col1 order by count(col1) desc
set @sql= ' '
set @c=1
while @c <=@ct1
select @sql=@sql+
',(select col2 from test a where col1=b.col1 and (select count(1) from test where col1=b.col1 and col2 <=a.col2)= '+
cast(@c as varchar(2))+ ') [ '+cast(@c as varchar(2))+ '] ',@c=@c+1
exec( 'select col1 '+@sql+ ' from test b group by col1 ')

col1 1 2 3
---- ---- ---- ----
a a1 a2 a3
b b1 b2 NULL
------解决方案--------------------
--假設第一列列名為A,第二列列名為B,如果A相同的時候,B不會重復
Create Table Test (A Varchar(10), B Varchar(10))

Insert Into TEST
Select 'a ', 'a1 '
Union All
Select 'a ', 'a2 '
Union All
Select 'b ', 'b1 '
Union All
Select 'b ', 'b2 '
GO
Declare @S Varchar(8000)
Select @S = 'Select A '
Select @S = @S + ', Max(Case OrderID When ' + Rtrim(OrderID) + ' Then B Else ' ' ' ' End) As B ' + Rtrim(OrderID)
From (Select *, OrderID =(Select Count(*) From TEST Where A = A.A And B <= A.B) From TEST A) B Group By OrderID
Select @S = @S + ' From (Select *, OrderID =(Select Count(*) From TEST Where A = A.A And B <= A.B) From TEST A) B Group By A '