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

一个简单的拼接写法求解
一个表中有二条记录;


aa     bb
-------------
12     cc
13     dd

我想要的结果是:

1     2  
------
cc     dd

求解

------解决方案--------------------
---测试
If Object_ID( 'T ') Is Not Null
Drop Table T
Go
Create Table T(aa int,bb varchar(10))
Insert T Select 12, 'cc '
Union All Select 13, 'dd '
Union All Select 14, 'ee '
Union All Select 15, 'ff '
Union All Select 16, 'gg '

Select * From T
Go
---表有没有主键,没有的话借用临时表
If Object_ID( 'TempDB..# ') Is Not Null
Drop Table #
Go
Select ID=Identity(int,1,1),bb Into # From T
---查询结果
Declare @sql Varchar(1000)
Set @sql= ' '
Select @sql=@sql+ ',Max(Case ID When ' ' '+Rtrim(ID)+ ' ' ' Then bb End) As [ '+Rtrim(ID)+ '] '
From # Group By ID
Set @sql=Stuff(@sql,1,1, ' ')
Exec( 'Select '+@sql+ 'From # ')
---结果
/*
(所影响的行数为 5 行)

aa bb
----------- ----------
12 cc
13 dd
14 ee
15 ff
16 gg

(所影响的行数为 5 行)


(所影响的行数为 5 行)

1 2 3 4 5
---------- ---------- ---------- ---------- ----------
cc dd ee ff gg

警告: 聚合或其它 SET 操作消除了空值。
*/
------解决方案--------------------
---如果你表aa是主键的话,那就不需要借助临时表了
/*下面这样*/
------------------------------------------------
Declare @sql Varchar(1000)
Set @sql= ' '
Select @sql=@sql+ ',Max(Case ID When ' ' '+Rtrim(ID)+ ' ' ' Then bb End) As [ '+Rtrim(ID)+ '] '
From (Select ID=(Select Count(1) From T Where aa <=A.aa),bb From T As A
) As TT Group By ID Order By ID
Set @sql=Stuff(@sql,1,1, ' ')
Exec( 'Select '+@sql+ 'From (Select ID=(Select Count(1) From T Where aa <=A.aa),bb
From T As A) As TT ')