您好我有下表,我想使用pivot功能:
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列上引发无效的列名错误。有人可以帮助识别错误吗?
答案 0 :(得分:2)
您可以使用以下角色:
;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
对于不同的列,您可以使用stuff来创建列列表,然后使用动态SQL来运行不同的列...但它可以在SO本身的各种示例中使用...
添加了我的输出:
答案 1 :(得分:0)
试试这个
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 ghut8695