Sql server SQL server:将行转换为列
CTE的输出:Sql server SQL server:将行转换为列,sql-server,pivot,Sql Server,Pivot,CTE的输出: colName ----------------------- branch1 branch1 branch1 unclassified 我想将行转换为列,如下所示: colName colName colName colName --------------------------------------------- unclassified branch1 branch1 branch1 请让我
colName
-----------------------
branch1
branch1
branch1
unclassified
我想将行转换为列,如下所示:
colName colName colName colName
---------------------------------------------
unclassified branch1 branch1 branch1
请让我知道最好的方法
提前谢谢 在没有看到完整查询的情况下,我建议在CTE中添加一个
行号()
,然后根据行号添加数据:
;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;
如果您不想使用PIVOT函数,那么还可以使用带有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
在没有看到完整查询的情况下,我建议在CTE中添加一个
行号()
,然后根据行号添加数据:
;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;
如果您不想使用PIVOT函数,那么还可以使用带有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
也许你想转换而不是康奈特?也许你想转换而不是康奈特?就是这样。阅读FROM语句中的选项。这正是它。阅读FROM语句中的选项。