2013-05-16 26 views
0

輸出:SQL服務器:從CTE轉換行到列

colName 
----------------------- 
branch1  
branch1  
branch1  
unclassified 

我想要的行轉換成列,如:

colName   colName colName colName 
--------------------------------------------- 
unclassified branch1 branch1 branch1 

請讓我知道這樣做的最好的辦法。

在此先感謝!

+0

也許你想**轉換**而不是** Conert **? –

回答

4

沒有看到完整的查詢基於行數我建議增加一個row_number()你的CTE,然後pivoting數據:

;with cte as 
(
    select *, -- replace * with your column names 
     ROW_NUMBER() over(partition by colName order by colName) rn 
    from yourdata 
) 
select [1] as colName1, 
    [2] as colName2, 
    [3] as colName3, 
    [4] as colName4 
from cte 
pivot 
(
    max(colName) 
    for rn in ([1], [2], [3], [4]) 
) piv; 

如果你不想使用旋轉功能,那麼你可以也可以使用具有CASE表達式的聚合函數:

;with cte as 
(
    select *, -- replace * with your column names 
     ROW_NUMBER() over(partition by colName order by colName) rn 
    from yourdata 
) 
select 
    MAX(case when rn = 1 then colName end) colName1, 
    MAX(case when rn = 2 then colName end) colName2, 
    MAX(case when rn = 3 then colName end) colName3, 
    MAX(case when rn = 4 then colName end) colName4 
from cte 
-- group by other columns in select if needed 
+0

就是這樣。在FROM語句中閱讀[T-SQL Pivot](http://msdn.microsoft.com/zh-cn/library/ms177634%28v=sql.105%29.aspx)選項。 – DougM