Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

pivot - SQL server : Convert rows into columns

Output from CTE:

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

I want to convert the rows into columns like:

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

Please let me know the best approach for this.

Thanks in advance!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without seeing your full query I would suggest adding a row_number() to your CTE and then pivoting the data based on the row number:

;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;

If you do not want to use the PIVOT function, then you could also use an aggregate function with a CASE expression:

;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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...