2016-03-11 34 views
1

我試圖將包含多行的結果錶轉換爲多列。下面是我的樣品結果之前和之後:將動態文本數據行轉換爲多列

前:

enter image description here

後:

enter image description here

得到了來自here一些想法,但仍然沒有運氣。

更新1:

select @cols = STUFF((select ',' + QUOTENAME(institution) + ',' +  QUOTENAME(intstatus) 
       From @temp 
       group by refno,frmstatus 
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

我不知道如何將每列插入樞軸查詢

set @query = 'select refno, frmstatus,' + @cols + ' 
from (
    select refno, frmstatus, institution, intstatus from #temp 
) x 
pivot 
(
??????? 
) 
+0

如果你發現我的答案有用,它爲你工作,請接受答案和/或upvote它,以便未來類似問題的尋求者發現這個問題很有用。你可以在這裏閱讀如何接受答案[http://stackoverflow.com/help/someone-answers] – DhruvJoshi

回答

1

請嘗試以下查詢:

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') 

接收到的結果產生:

enter image description here

0

如果重複列數量少,限制,你可以使用簡單的解決方案:

WITH A AS (
SELECT *, 
ROW_NUMBER() OVER(PARTITION BY refno, fmstatus ORDER BY institution) n 
FROM myTable 
), 

B AS (
SELECT refno, fmstatus, 
CASE WHEN n=1 THEN institution END institution, 
CASE WHEN n=1 THEN intstatus END intstatus, 
CASE WHEN n=2 THEN institution END institution1, 
CASE WHEN n=2 THEN intstatus END intstatus1, 
CASE WHEN n=3 THEN institution END institution2, 
CASE WHEN n=3 THEN intstatus END intstatus2 
FROM A 
) 

SELECT refno, fmstatus, 
MAX(institution) institution, 
MAX(intstatus) intstatus, 
MAX(institution1) institution1, 
MAX(intstatus1) intstatus1, 
MAX(institution2) institution2, 
MAX(intstatus2) intstatus2 
FROM B 
GROUP BY refno, fmstatus 

否則使用PIVOT

+0

有可能,結果需要超過3個機構和intstatus列。 – soniality