我只有以下两个表定义
CREATE TABLE ICD ([EpiNum] varchar(4), [ICDCode] varchar(4));
GO
INSERT INTO ICD ([EpiNum], [ICDCode])
VALUES
('1', 'A1'),
('1', 'A2'),
('1', 'A3'),
('2', 'B1'),
('2', 'B2'),
('3', 'C3');
GO
CREATE TABLE TempEpisode ([EpiNum] varchar(4), [X1] varchar(4), [X2] varchar(4), [X3] varchar(4));
GO
INSERT INTO TempEpisode ([EpiNum], [X1], [X2], [X3])
VALUES
('1', '', '', ''),
('2', '', '', ''),
('3', '', '', '');
GO
我想知道如何更新TempEpisode
以便我
('1', 'A1', 'A2', 'A3'),
('2', 'B1', 'B2', ''),
('3', 'C3', '', '');
作为输出?请注意,EpiNum
有3个代码,EpiNum
2代码为2,EpiNum
为1代表3.我想要按列分组这些副本。
我做了什么......我最初开始采用数据透视表方式;这已经变得复杂了,我不完全确定如何从中得到我需要的东西。我现有的代码是
DECLARE @cols AS NVARCHAR(MAX), @columns AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(ICDCode)
FROM ICD
GROUP BY ICDCode
ORDER BY ICDCode
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
PRINT @cols;
SELECT @columns =
STUFF((SELECT ', coalesce(' +
QUOTENAME(ICDCode)+', '''') as ' +
QUOTENAME('X' + ICDCode)
FROM ICD
GROUP BY ICDCode
ORDER BY ICDCode
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
SET @query = 'SELECT EpiNum, ' + @columns + '
FROM
(
SELECT EpiNum, ICDCode, ICDCode AS flag
FROM ICD
) AS x
PIVOT
(
MAX(flag)
FOR ICDCode IN (' + @cols + ')
) AS p ';
execute(@query);
这会产生:
EpiNum XA1 XA2 XA3 XB1 XB2 XC3
1 A1 A2 A3
2 B1 B2
3 C3
我想要
EpiNum XA1 XA2 XA3
1 A1 A2 A3
2 B1 B2
3 C3
答案 0 :(得分:1)
试试这个
insert TempEpisode
select *
from
(
select *, ROW_NUMBER() over (partition by epinum order by icdcode) rn
from ICD
) p
pivot (max(icdcode) for rn in ([1],[2],[3])) p2
您需要考虑的事情。