选择两个表之间的最高记录

时间:2017-11-07 10:54:28

标签: sql postgresql

我有两张桌子。一个表包含毕业记录,第二个表包含毕业记录。候选人必须有毕业,但不一定要毕业。

我的问题是如果候选人毕业后只选择毕业,那么选择毕业后的记录。

表1 gradu_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

4 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:1)

您希望graduation_tablepostgraduation_table中没有行的所有行加上postgraduation_table中的行。not exists。这可以用unionselect 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; 查询表示:

{{1}}

在线示例:http://rextester.com/IFCQR67320

答案 2 :(得分:0)

获取两个表的并集,并引入一个位置列,以对两个表的相对重要性进行排名。研究生课程的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;

答案 3 :(得分:0)

这应该满足您的需求:

SELECT dg.rollno, CASE WHEN pg IS NOT NULL THEN pg.degree ELSE gd.degree END AS degree, dg.division
  FROM graduation_table AS dg
  LEFT OUTER JOIN postgraduation_table AS pg USING (rollno)
 GROUP BY dg.rollno, dg.division;

希望得到这个帮助。