问题
I have 2 tables (simplified for this example) which I want to join in a particular way.
- Table 1 (ae) has subject number, ae term
- Table 2 (mh) has subject number, mh term
heres the construct to help
INSERT INTO ae VALUES ('0001-0012','DRY EYE (12 OCT 2017)');
INSERT INTO ae VALUES ('0001-0012', 'DEPRESSION (7 OCT 2017)');
INSERT INTO ae VALUES ('0001-0013','SKIN ATROPHY, LEFT UPPER ARM (4 OCT 2017 )');
INSERT INTO mh VALUES ('0001-0012', 'DIABETES MELLITUS (UN JUL 2007)');
INSERT INTO mh VALUES ('0001-0012', 'GASTRO-ESOPHAGEAL REFLUX INTERMITENT GR1 (18 AUG 2017)');
INSERT INTO mh VALUES ('0001-0012', 'ESOPHAGITIS GR 1 (18 AUG 2017)');
INSERT INTO mh VALUES ('0001-0012', 'DIARRHEA INITERMITTENT GR2 (5 JUL 2017 )');
INSERT INTO mh VALUES ('0001-0012', 'FATIGUE INTERMITTENT GR1 (18 AUG 2017)');
INSERT INTO mh VALUES ('0001-0013', 'VOMITING, INTERMITTENT GR1 (6 JUL 2017 )');
I want my output to look like this:
Any help out there? As you can see its a gnarly join I need!
回答1:
You can use row_number()
and full join
:
select coalesce(ae.col1, mh.col1) as col1, ae.col2, mh.col2
from (select ae.*, row_number() over (partition by col1 order by col1) as seqnum
from ae
) ae full join
(select mh.*, row_number() over (partition by col1 order by col1) as seqnum
from mh
) mh
on mh.col1 = ae.col1 and mh.seqnum = ae.seqnum
order by coalesce(ae.col1, mh.col1), seqnum;
回答2:
heres my updated code so far it now gives me the correct order EDIT Just added the DESC at the end of the code to give me the result
select coalesce(ae.subject, mh.subject) as subject, ae.aeterms, mh.mhterms
from (select ae.*, row_number() over (partition by subject order by subject)
as seqnum
from ae) ae full join
(select mh.*, row_number() over (partition by subject order by subject) as
seqnum from mh) mh
on mh.subject = ae.subject and mh.seqnum = ae.seqnum
order by coalesce(ae.subject, mh.subject), ae.seqnum Desc;
来源:https://stackoverflow.com/questions/48911535/sql-cartesian-type-join