所有我有以下两个表定义
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', '', '');
作为输出?请注意,1 有 3 个代码EpiNum
,2EpiNum
有2 个代码,3 有 1 个代码EpiNum
。所以我想按列对这些重复项进行分组。
我做了什么...我最初着手采用数据透视表方法;这变得很复杂,我不完全确定如何从中得到我需要的东西。我现有的代码是
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