这是一个我知道的流行问题。我刚刚学习数据透视表,不知道我哪里出错了。
create table #test
(
id varchar(4),
code varchar(2),
received_dt varchar(8)
)
insert into #test values ('1234','10','20150312')
insert into #test values ('1234','71','20150312')
insert into #test values ('1234','C5','20150312')
insert into #test values ('4321','10','20150312')
insert into #test values ('4321','71','20150312')
insert into #test values ('987','10','20150312')
insert into #test values ('987','71','20150312')
insert into #test values ('987','C5','20150312')
select id, [code1], [code2], [code3]
from #test
pivot(MAX(code) for code in ([code1], [code2], [code3])) as pvt
drop table #test
非常感谢任何帮助/指导。我知道这应该很容易,但我似乎无法将我的大脑包裹起来。
结果:
ID Code1 Code2 Code3
1234 NULL NULL NULL
4321 NULL NULL NULL
987 NULL NULL NULL
想要:
ID Code1 Code2 Code3
1234 10 71 C5
4321 10 71 NULL
987 10 71 C5
编辑有许多代码值。
答案 0 :(得分:3)
您需要创建另一个包含Code1, Code2, Code3
值的列:
;WITH CTE AS
(
SELECT *,
RN = 'Code' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY code) AS CHAR(1))
FROM #test
)
SELECT id, [code1], [code2], [code3]
FROM CTE
PIVOT(MAX(code) for RN in ([code1], [code2], [code3])) as pvt;
<强>更新强>
如果您的代码数量未知,则需要动态SQL:
DECLARE @sql NVARCHAR(MAX) = N'', @cols NVARCHAR(MAX) = N'';
WITH CTE AS
(
SELECT *,
RN = 'Code' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY code) AS CHAR(1))
FROM #test
)
SELECT @cols += STUFF((SELECT ',' + QUOTENAME(RN)
FROM CTE
GROUP BY RN
FOR XML PATH('')), 1, 1, '');
SET @sql = N'
SELECT *
FROM ( SELECT *,
RN = ''Code'' +
CAST(ROW_NUMBER() OVER(PARTITION BY ID ORDER BY code) AS CHAR(1))
FROM #test) AS d
PIVOT(MAX(code) for RN in (' + @cols + ')) AS p;';
EXEC sp_executesql @sql;