0

所有我有以下两个表定义

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
4

1 回答 1

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

你需要考虑的事情。

  1. 您如何定义剧集的顺序 - 是否有未显示的额外字段?
  2. 这是个好主意吗 - 为什么要对数据进行非规范化?
于 2013-10-01T21:52:36.480 回答