請嘗試以下查詢:
CREATE TABLE #temp(refno nvarchar(20), firmstatus nvarchar(20), institution nvarchar(20), intstatus nvarchar(20), ranking int)
DECLARE @qu NVARCHAR(MAX), @pcol NVARCHAR(MAX)
INSERT INTO #temp
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY refno ORDER BY institution ASC) AS ranking
FROM temp
SELECT @pcol=
STUFF((
SELECT
DISTINCT N', Institution'+ CAST (ranking AS NVARCHAR(25)) +', '+ N'Intstatus'+ CAST (ranking AS NVARCHAR(25))
FROM #temp
FOR XML PATH('')),1,1,'')
SET @qu=N'SELECT refno, firmstatus,'+ @pcol +
N' FROM
(
select refno,firmstatus,ColData,colheader+ CAST(ranking as varchar) as colnames from
(select * from #temp)s
UNPIVOT
(ColData for colheader in ([institution], [intstatus])) up
)S
PIVOT
(MAX(ColData) FOR colnames IN ('[email protected] +N')) AS piv'
EXEC sp_executesql @qu -- execute the dynamic sql
DROP TABLE #temp -- remove the temp table
在上面的腳本中的臨時表是像下面
--create table temp(refno nvarchar(20), firmstatus nvarchar(20), institution nvarchar(20), intstatus nvarchar(20))
--insert into temp values
--('AAA/1','Active','InstA','Ongoing'),
--('AAA/1','Active','InstB','Ongoing'),
--('AAA/1','Active','InstC','Ongoing'),
--('AAA/2','Active','InstA','Ongoing'),
--('AAA/2','Active','InstB','Ongoing')
接收到的結果產生:
如果你發現我的答案有用,它爲你工作,請接受答案和/或upvote它,以便未來類似問題的尋求者發現這個問題很有用。你可以在這裏閱讀如何接受答案[http://stackoverflow.com/help/someone-answers] – DhruvJoshi