我有一张看起来像这样的表:
country + form_ID + Original_form_Id + catalog
country original_form catalog form_id
1 6 42 6
1 7 368 7
1 69 722 69
1 69 1837 697
1 659 2 659
1 666 2 666
original_form_id和form id:它总是相等的,除了的情况 country + original_form-id转到不同的目录,意思是这行:
country original_form catalog form_id
1 69 722 69
1 69 1837 697
我需要从中创建3个表。一个表用于所有行1:1(国家+ original_form到目录),第二个N:1和第三个1:N个案例。含义:
第一张表1:1
country original_form catalog
1 6 42
1 7 368
第二表1:N
country original_form catalog
1 69 722
1 69 1837
第三张桌子N:1
country original_form catalog
1 659 2
1 666 2
我使用下面的答案实现它,但有重复:
INSERT INTO Mapping_1ToN
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE EXISTS -- Multiple catalogs for same country+form
(
SELECT *
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND ot1.original_form_id = ot2.original_form_id
AND ot1.form_id <> ot2.form_id
AND ot1.catalog_id <> ot2.catalog_id
));
INSERT INTO Mapping_NTo1
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE EXISTS -- Multiple forms for same catalog
(
SELECT *
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND ot1.original_form_id <> ot2.original_form_id
AND ot1.catalog_id = ot2.catalog_id
));
INSERT INTO Mapping_1To1
(SELECT ot1.Country_id, ot1.original_form_id, ot1.catalog_id, ot1.Local_id
FROM mappingtable ot1
WHERE NOT EXISTS -- form+catalog unique per country
(
SELECT ot2.Country_id, ot2.original_form_id, ot2.catalog_id, ot2.Local_id
FROM mappingtable ot2
WHERE ot1.country_id = ot2.country_id
AND (
(ot1.original_form_id = ot2.original_form_id AND ot1.catalog_id <> ot2.catalog_id AND ot1.form_id = ot2.form_id)
OR
(ot1.original_form_id <> ot2.original_form_id AND ot1.catalog_id = ot2.catalog_id)
)
));
答案 0 :(得分:1)
第一张表:
insert Table1
select *
from OriginalTable ot1
where not exists -- form+catalog unique per country
(
select *
from OriginalTable ot2
where ot1.country = ot2.country
and (
(ot1.form = ot2.form and ot1.catalog <> ot2.catalog)
or
(ot1.form <> ot2.form and ot1.catalog = ot2.catalog)
)
)
第二张表:
insert Table2
select ot1.*
from OriginalTable ot1
where exists -- Multiple catalogs for same country+form
(
select *
from OriginalTable ot2
where ot1.country = ot2.country
and ot1.form = ot2.form
and ot1.catalog <> ot2.catalog
)
第三张表:
insert Table3
select ot1.*
from OriginalTable ot1
where exists -- Multiple forms for same country+catalog
(
select *
from OriginalTable ot2
where ot1.country = ot2.country
and ot1.form <> ot2.form
and ot1.catalog = ot2.catalog
)
要查找最终会出现在Table2和Table3中的行,请运行:
select *
from OriginalTable ot1
where exists
(
select *
from OriginalTable ot2
where ot1.country = ot2.country
and ot1.form <> ot2.form
and ot1.catalog = ot2.catalog
)
and exists
(
select *
from OriginalTable ot2
where ot1.country = ot2.country
and ot1.form = ot2.form
and ot1.catalog <> ot2.catalog
)