I have a table that looks something like that:
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
The point of original_form_id and form id: it is always equal, besides the case of
country +original_form-id that go to different catalogs, meaning in this rows:
country original_form catalog form_id
1 69 722 69
1 69 1837 697
I need to create from it 3 tables. One table is for all rows 1:1 (country+original_form to catalog), Second N:1 and Third 1:N cases. Meaning:
First table 1:1
country original_form catalog
1 6 42
1 7 368
Second table 1:N
country original_form catalog
1 69 722
1 69 1837
Third table N:1
country original_form catalog
1 659 2
1 666 2
I implement it using the answer bellow but there are duplicates:
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)
)
));
First table:
Second table:
Third table:
To find rows that would end up in both Table2 and Table3, run: