小编典典

需要在SQL Server中透视字符串值

sql

我将表描述为:

Occupation String |
Name String

带有值:

Developer | A
Developer | B
Designer  | X
Coder     | Y
Coder     | Z

我需要以下数据透视格式的值:

Designer | Developer | Coder
---------+-----------+--------   
   X     |     A     |   Y
   Null  |     B     |   Z

有人可以帮忙吗?

提前致谢


阅读 189

收藏
2021-05-23

共1个答案

小编典典

具有ROW_NUMBER()的基本PIVOT将为您完成以下任务:

SELECT  [Developer],
        [Designer],
        [Coder]
FROM (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
    FROM #temp
) as t
PIVOT (
    MAX(Name) FOR Occupation IN ([Developer],[Designer],[Coder])
) as pvt

输出:

Developer   Designer    Coder
A           X           Y
B           NULL        Z

如果的数量Occupation可能非常多,则您需要动态SQL:

DECLARE @columns nvarchar(max),
        @sql nvarchar(max)

SELECT @columns = (
    SELECT DISTINCT ','+QUOTENAME(Occupation)
    FROM #temp
    FOR XML PATH('')
)

SELECT @sql = N'
SELECT  '+STUFF(@columns,1,1,'')+'
FROM (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
    FROM #temp
) as t
PIVOT (
    MAX(Name) FOR Occupation IN ('+STUFF(@columns,1,1,'')+')
) as pvt'

EXEC sp_executesql @sql

注意:ORDER BY (SELECT NULL)只是用来获得一些随机顺序。为此,最好使用一些实际字段。

2021-05-23