我有一些结构良好的数据,如下所示:
CREATE TABLE SourceBodyPartColors
(
person_ID INTEGER NOT NULL,
body_part_name VARCHAR(5) NOT NULL
CHECK (body_part_name IN ('hair', 'eye', 'teeth')),
color VARCHAR(20) NOT NULL,
UNIQUE (color, body_part_name, person_ID)
);
INSERT INTO SourceBodyPartColors (person_ID, body_part_name, color)
VALUES (1, 'eye', 'blue'),
(1, 'hair', 'blond'),
(1, 'teeth', 'white'),
(2, 'hair', 'white'),
(2, 'teeth', 'yellow'),
(3, 'hair', 'red');
可悲的是,目标结构并不那么好看,看起来更像是这样:
CREATE TABLE TargetBodyPartColors
(
person_ID INTEGER NOT NULL UNIQUE,
eye_color VARCHAR(20),
hair_color VARCHAR(20),
teeth_color VARCHAR(20)
);
INSERT INTO TargetBodyPartColors (person_ID)
VALUES (1), (2), (3);
我可以像这样写一个SQL-92 UPDATE
:
UPDATE TargetBodyPartColors
SET eye_color = (
SELECT S1.color
FROM SourceBodyPartColors AS S1
WHERE S1.person_ID
= TargetBodyPartColors.person_ID
AND S1.body_part_name = 'eye'
),
hair_color = (
SELECT S1.color
FROM SourceBodyPartColors AS S1
WHERE S1.person_ID
= TargetBodyPartColors.person_ID
AND S1.body_part_name = 'hair'
),
teeth_color = (
SELECT S1.color
FROM SourceBodyPartColors AS S1
WHERE S1.person_ID
= TargetBodyPartColors.person_ID
AND S1.body_part_name = 'teeth'
);
......但重复的代码困扰着我。
我认为,使用MERGE
进行简化是一个很好的结果,但我无法提出任何合理的建议。
有关如何将MERGE
与此数据一起使用的任何想法。 (注意:我想避免使用专有UPDATE..FROM syntax
,谢谢。)
答案 0 :(得分:6)
WITH Pivoted AS
(
SELECT person_ID, eye, hair, teeth
FROM SourceBodyPartColors
PIVOT
(
MAX (color) FOR body_part_name IN ( [eye], [hair], [teeth] )
) AS pvt
)
MERGE TargetBodyPartColors AS target
USING Pivoted AS source
ON (target.person_ID = source.person_ID)
WHEN MATCHED THEN
UPDATE SET eye_color = source.eye,
hair_color = source.hair,
teeth_color = source.teeth ;