1

我已经用谷歌搜索过了

  
 I have a Table with following structure in SQL 2000

 ID ContactName Designation
 1  A           CEO
 2  B           ABC
 3  C           DEF
 4  D           GHI

我需要输出如下


ContactName1 Contactname2 ContactName3 ContactName4
 A CEO        B ABC         C DEF         D GHI

有什么建议么 ?

4

4 回答 4

1

您需要使用数据透视表

于 2009-01-14T12:13:53.787 回答
1

这也适用于 2000 - wg。没有枢轴

http://www.sqlteam.com/item.asp?ItemID=2955

于 2009-01-14T12:20:59.480 回答
1

另一个 SQL Cross Tab proc http://johnmacintyre.ca/codespct.asp

于 2009-01-14T12:23:27.853 回答
1

在我看来,很多示例都是针对涉及聚合的交叉表查询,而您的似乎不需要。虽然我不一定宽恕动态 SQL,但下面应该会给你你想要的结果。

Create table #Contacts (id int)
Declare @ContactTypes int
Declare @CAD varchar(100)
Declare @I int
Declare @sql nvarchar(4000)
Set @i = 1
Select @ContactTypes =   
Sum(sub.Types) 
from ( Select Count(1) as Types from contacts
group by ContactName, Designation) as sub
Print @ContactTypes
While @i <= @ContactTypes
Begin
    set @sql = 'alter table #Contacts Add  ContactName' + 
    Cast(@I as varchar(10)) + ' varchar(100)'
    exec sp_executesql @sql
    Set @I = @i + 1
End
Insert into #Contacts (id) values (1)
Set @i = 1
Declare crsPivot  cursor 
for Select ContactName + ' ' + Designation
from contacts
open crsPivot
Fetch next from crsPivot into @CAD
While (@@Fetch_Status = 0)
Begin   
    Set @sql = 'Update  #Contacts  set ContactName' 
    + Cast(@I as varchar(10)) +' = ' + quotename(@CAD,'''')
    exec sp_executesql @sql
    Set @i = @i + 1
    Fetch next from crsPivot into @CAD
End
close crsPivot
Deallocate crsPivot
select * From #Contacts
于 2009-01-14T13:09:09.557 回答