带有Pivot的动态插入

时间:2013-10-01 21:37:58

标签: sql sql-server sql-server-2008

我只有以下两个表定义

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

1 个答案:

答案 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

您需要考虑的事情。

  1. 如何定义剧集的顺序 - 是否有一个未显示的额外字段?
  2. 这是一个好主意 - 为什么要对数据进行去标准化?