我有以下两张表;ICD
创建使用
CREATE TABLE ICD ([E] VARCHAR(8), [I] VARCHAR(8));
GO
INSERT INTO ICD ([E], [I])
VALUES
('1', 'B1'),
('1', 'A1'),
('1', 'C23q'),
('1', '32Dq'),
('2', 'FFFq'),
('2', 'ERRE'),
('2', 'E'),
('3', 'WQWW'),
('3', 'WQ'),
('4', 'AAAA');
GO
whereO
给出了将列I
插入另一个表的顺序。第二个表是Episode
,这是使用创建的
CREATE TABLE Episode ([EpiNum] VARCHAR(4), [SomeField] VARCHAR(4),
[DX1] VARCHAR(10), [DX2] VARCHAR(10),
[DX3] VARCHAR(10), [DX4] VARCHAR(10));
GO
INSERT INTO Episode ([EpiNum], [SomeField], [DX1], [DX2], [DX3], [DX4])
VALUES
('1', 'Test', '', '', '', ''),
('2', 'Test', '', '', '', ''),
('3', 'Test', '', '', '', '');
GO
所以我的目标是根据是否有要插入的值将列I
中的值插入ICD
到DXn
字段中。忍受我;我有这个工作使用
MERGE INTO [Episode] AS T
USING (
SELECT [EpiNum], [1], [2], [3], [4]
FROM
(
SELECT *, ROW_NUMBER()
OVER (PARTITION BY [EpiNum] ORDER BY [I]) AS rn
FROM [ICD]
) AS p
PIVOT
(
MAX([I])
FOR rn IN ([1], [2], [3], [4])) AS p2
) AS S
ON T.[EpiNum] = S.[EpiNum]
WHEN MATCHED THEN
UPDATE SET [DX1] = S.[1], [DX2] = S.[2], [DX3] = S.[3], [DX4] = S.[4];
这会产生一个Episode
看起来像的表格
EpiNum Test DX1 DX2 DX3 DX4
'1' 'Test' '32Dq' 'A1' 'B2' 'C23q'
'2' 'Test' 'E' 'ERRE' 'FFFq' null
'3' 'Test' 'WQ' 'WQWW' null null
'4' 'Test' 'AAAA' null null null
伟大的!等等...不太好,ORDER BY
PIVOT/MERGE 中的 破坏了数据的原始顺序。我试图通过添加另一个O
包含我想要的顺序的列来解决这个问题,所以ICD
定义为
CREATE TABLE ICD ([E] VARCHAR(8), [I] VARCHAR(8), [O] INT);
GO
INSERT INTO ICD ([E], [I], [O])
VALUES
('1', 'B1.2', 1),
('1', 'A1.2', 2),
('1', 'C23q', 3),
('1', '32Dq', 4),
('2', 'FFFq', 1),
('2', 'ERRE', 2),
('3', 'WQWW', 1),
('4', 'AAAA', 1);
GO
我正在ORDER BY
尝试O
使用
MERGE INTO [Episode] AS T
USING (
SELECT [E], [1], [2], [3], [4]
FROM
(
SELECT *, ROW_NUMBER()
OVER (PARTITION BY [E] ORDER BY [O]) AS rn
FROM [ICD]
) AS p
PIVOT
(
MAX([I])
FOR rn IN ([1], [2], [3], [4])) AS p2
) AS S
ON T.[E] = S.[E]
WHEN MATCHED THEN
UPDATE SET [DX1] = S.[1], [DX2] = S.[2], [DX3] = S.[3], [DX4] = S.[4];
但我收到以下消息
MERGE 语句多次尝试更新或删除同一行。当目标行匹配多个源行时会发生这种情况。MERGE 语句不能多次 UPDATE/DELETE 目标表的同一行。优化 ON 子句以确保目标行最多匹配一个源行,或使用 GROUP BY 子句对源行进行分组。
如何修改上述内容MERGE/PIVOT
以正确订购?
谢谢你的时间