我有两张桌子。一个表包含毕业记录,第二个表包含毕业后记录。应聘者必须毕业,但不一定要毕业后。
我的问题是,如果应聘者有岗位毕业记录,则选择岗位毕业记录,否则只有毕业记录。
表1 graduation_table
rollno | degree | division
--------------------------
001 | B.tech | 1st
002 | B.sc | 1st
003 | BA | 1st表2 postgraduation_table
rollno | degree | division
--------------------------
002 | M.sc | 1st结果必须为
rollno | degree | division
--------------------------
001 | B.tech | 1st
002 | M.sc | 1st
003 | BA | 1st发布于 2017-11-07 19:03:07
您需要graduation_table中没有postgraduation_table行的所有行以及postgraduation_table中的行。这可以用not exists和union查询来表示:
select gt.rollno, gt.degree, gt.division
from graduation_table gt
where not exists (select *
from postgraduation_table pg
where pg.rollno = gt.rollno)
union all
select rollno, degree, division
from postgraduation_table
order by rollno;在线示例:http://rextester.com/IFCQR67320
发布于 2017-11-07 19:02:08
select
rollno,
case when p.degree is null then g.degree else p.degree end as degree,
case when p.division is null then g.division else p.division end as division
from
grad g
left join
post p using (rollno)或者像评论中建议的那样更好:
select
rollno,
coalesce (p.degree, g.degree) as degree,
coalesce (p.division, g.division) as division
from
grad g
left join
post p using (rollno)发布于 2017-11-07 18:58:26
将这两个表合并,并引入一个position列,以对这两个表的相对重要性进行排名。研究生表的pos值为1,研究生表的值为2。然后,对此联合查询应用ROW_NUMBER(),并为每个rollno记录组分配一个行号(假定为一条或最多两条记录)。最后,再执行一个外部子查询以保留最重要的记录,首先是研究生,其次是研究生。
SELECT rollno, degree, division
FROM
(
SELECT
rollno, degree, division,
ROW_NUMBER() OVER (PARTITION BY rollno ORDER BY pos) rn
FROM
(
SELECT p.*, 1 AS pos p FROM postgraduation_table
UNION ALL
SELECT p.*, 2 FROM graduation_table p
) t
) t
WHERE t.rn = 1;https://stackoverflow.com/questions/47156122
复制相似问题