質問

このためにグーグルで検索しました

  
 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

提案はありますか?

役に立ちましたか?

解決

多くの例は、集計を必要とするクロスタブクエリ用であり、これは必要ないと思われます。動的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

他のヒント

PIVOTEDテーブル

を使用する必要があります

これは2000でも動作するはずです-wg。ピボットなし

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

さらに別のSQLクロスタブプロシージャ http://johnmacintyre.ca/codespct.asp

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top