您没有告诉您的 RDMS,但以下代码适用于 Oracle(和 SQL Server,我想)。对于其他人,有row_number
功能仿真。
--creating table..
CREATE TABLE "YOURTABLE"
( "TIP" VARCHAR2(20),
"IDE" NUMBER
)
--inserting experimental values..
insert into YOURTABLE (TIP, IDE)
values ('History', 1);
insert into YOURTABLE (TIP, IDE)
values ('History', 1);
insert into YOURTABLE (TIP, IDE)
values ('Geography', 1);
insert into YOURTABLE (TIP, IDE)
values ('Geography', 2);
insert into YOURTABLE (TIP, IDE)
values ('French', 2);
insert into YOURTABLE (TIP, IDE)
values ('French', 3);
insert into YOURTABLE (TIP, IDE)
values ('English', 3);
insert into YOURTABLE (TIP, IDE)
values ('English', 4);
insert into YOURTABLE (TIP, IDE)
values ('History', 4);
insert into YOURTABLE (TIP, IDE)
values ('History', 4);
--code..
select m.*
from (select *
from YOURTABLE
where tip = 'History'
union
select *
from YOURTABLE
where tip = 'Geography'
and ide not in (select ide from YOURTABLE where tip = 'History')
union
select tip, ide
from (select s.*,
ROW_NUMBER() OVER(PARTITION BY ide ORDER BY ide) ord
from YOURTABLE s
where tip not in ('History', 'Geography')
and ide not in
(select ide
from YOURTABLE
where tip in ('History', 'Geography')))
where ord = 1) m
结果表:
TIP IDE
-------------------- ----------
History 1
Geography 2
English 3
History 4
你说:
历史、地理和所有其他的“类型层次结构”
在我的示例中,结果是英语而不是法语,但这不应该成为问题,因为“所有其他人”都是平等的。