嗨,我有下表,我想使用枢轴函数:
Id|Number| Code
1 | 34 |abc12345
1 | 23 |xqwe6758
2 | 37 |ghut564hg
3 | 456 |ghut8695
3 | 39 |ghtuj678
3 | 22 |fsdifje12我希望它水平地显示如下:
Id| Code1 | Code2 | Code3
1 | abc12345 | xqwe6758 | null
2 |ghut564hg | null | null
3 |ghut8695 | ghtuj678 | fsdifje12
SELECT Id
,[Code1]
,[Code2]
,[Code3]
FROM(SELECT Id,Code
FROM [TableName]
)d
pivot(
max(Id)
for Code in([Code1],[Code2],[Code3])
)as piv;这会在Id列上引发无效的列名错误。有人能帮忙识别错误吗?
发布于 2016-12-07 20:52:28
可以使用枢轴,如下所示:
;with cte as
(
select
id, code,
RowN = Row_Number() over (partition by id order by code)
from
yourtable1
)
select *
from cte
pivot ( max(code) for RowN in([1], [2], [3])) p对于不同的列,您可以使用SQL创建列列表,然后使用动态SQL以不同的列运行.但它本身在各种例子中都是可用的。
添加了我的输出:

发布于 2016-12-07 20:56:11
尝尝这个
DECLARE @tbl TABLE(Id INT, Code VARCHAR(100));
INSERT INTO @tbl VALUES
(1,'abc12345')
,(1,'xqwe6758')
,(2,'ghut564hg')
,(3,'ghut8695')
,(3,'ghtuj678')
,(3,'fsdifje12');
SELECT p.*
FROM
(
SELECT Id
,'Code' + CAST(ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Code) AS VARCHAR(10)) AS ColumnName
,Code
FROM @tbl
) AS t
PIVOT
(
MAX(Code) FOR ColumnName IN(Code1,Code2,Code3 /*add as many as you need*/)
) AS p结果
Id Code1 Code2 Code3
1 abc12345 xqwe6758 NULL
2 ghut564hg NULL NULL
3 fsdifje12 ghtuj678 ghut8695https://stackoverflow.com/questions/41026882
复制相似问题