2016-10-12 60 views
3

我有臨時表中的數據。在sql server中將兩列轉換爲5行

select * 
from #test 

程序這樣的輸出:

reg | Years 
--------------- 
6279 | 2016 
6641 | 2016 
8347 | 2016 
6228 | 2015 
8596 | 2015 
7596 | 2015 
6352 | 2015 
1245 | 2014 
5248 | 2014 
6359 | 2014 
6785 | 2014 
9578 | 2013 
4398 | 2013 
2986 | 2013 
7296 | 2013 

但上表中我需要在5行顯示。它意味着將列轉換爲下面的行示例

years | reg1 | reg2 | reg3 | reg4 
------+------+------+------+----- 
2016 | 6279 | 6641 | 8347 | NULL 
2015 | 6228 | 8596 | 7596 | 6352 
2014 | 1245 | 5248 | 6359 | 6785 
2013 | 9578 | 4398 | 2986 | 7296 

我嘗試使用pivot和unpivot作爲每個建議,但仍然沒有得到。請幫幫我。

回答

4

這裏是一個動態實現使用CROSS TAB

DECLARE @sql  VARCHAR(max)='', 
     @intr  INT = 1, 
     @cnt  INT 

SELECT @cnt = (SELECT (Max([Years]) - Min([Years])) + 1 
        FROM Yourtable) 

SET @sql = 'select [Years], ' 

WHILE @intr <= @cnt 
    BEGIN 
     SET @sql += 'max(case when rn = '+ Cast(@intr AS VARCHAR(4)) + ' then [reg] end) as [reg' 
        + Cast(@intr AS VARCHAR (100)) + '],' 
     SET @intr+=1 
    END 

SET @sql = LEFT(@sql, Len(@sql) - 1) 

SELECT @sql += 'from (select row_number()over(partition by [Years] order by [reg]) as rn,* from Yourtable) a group by [Years]' 

--SELECT @sql 

EXEC(@sql) 
2

對於記錄的數量有限,每年你可以在靜態SQL查詢中使用條件聚集

;WITH temp_with_rn AS (
    SELECT eg, years, ROW_NUMBER() OVER (PARTITION BY Years ORDER BY eg) AS rn 
    FROM temp 
) 
SELECT years, 
     MAX(CASE WHEN rn = 1 THEN eg END) AS reg1, 
     MAX(CASE WHEN rn = 2 THEN eg END) AS reg2, 
     MAX(CASE WHEN rn = 3 THEN eg END) AS reg3, 
     MAX(CASE WHEN rn = 4 THEN eg END) AS reg4 
FROM temp_with_rn 
GROUP BY years 
+0

我有一個疑問......我們在用usin克Max()函數在查詢....如果我們使用最大值將先來....但我不需要..請幫助我...在其他解決方案 –

1

使用PIVOT :

Select * from 
(Select *, 'reg' + cast(row_number() over(partition by year order by reg) as varchar(5)) RowVal 
from table) x 
PIVOT 
(
MAX(reg) FOR RowVal in ([reg1], [reg2], [reg3], [reg4]) 
) y 
order by year desc