Postgresql在两个具有相同列的表中获取原始值

时间:2014-09-16 06:38:14

标签: sql postgresql

我有以下两个表

Table_one

school_id subjec_code   student_count
0001      S1            25
0001      S2            10
0002      S1            38
0002      S2            12

Table_two

school_id subject_code techer_count
0001      S2           2
0001      S1           3
0002      S1           1
0002      S2           2


Result I want is 

school_id subject student_count teacher_count
0001      s1      25            3
0001      s2      10            2
0002      s1      38            1

我尝试加入这两个表格并支持school_id和subject_code,但我无法获得每个主题的相关计数。

2 个答案:

答案 0 :(得分:1)

如果您确定两个表中的所有学校/子代码都有记录,则可以删除FULL OUTER部分。

SELECT Table_one.school_id, Table_one.subjec_code as subject, Table_one.student_count,
     Table_two.subjec_code, Table_two.teacher_count
    FROM Table_one FULL OUTER JOIN  Table_two
    ON Table_one.school_id = Table_two.school_id
    AND Table_one.subjec_code = Table_two.subjec_code
    ORDER BY table_one.school_id, Table_one.subjec_code;

您在一个表中有subjec_code,在另一个表中有subject_code。我在两者中都使用了subjec_code。

答案 1 :(得分:0)

尝试此查询,这将解决您的问题

SELECT Table_one.school_id, Table_one.subject_code as subject, Table_one.student_count,
     Table_two.subject_code, Table_two.teacher_count
    FROM Table_one, Table_two
    WHERE Table_one.school_id = Table_two.school_id;