从一个表中选择所有内容,从一个表中选择一些关于SQL加入2个变量的表

时间:2015-07-24 20:20:23

标签: sql postgresql querying

我很难从两张桌子中选择数据。 我尝试使用每个连接但无法弄明白。 我正在使用Postgresql

这些是我的表格: TABLE_A

date, class, count_of_a
4/1/2015, B, 888
4/2/2015, A, 533
4/2/2015, A, 432
4/3/2015, C, 484

表-B

date, class, count_of_b
4/2/2015, B, 345
4/3/2015, D, 553
4/3/2015, C, 334

我希望这是我的结果:

date, class, count_of_a, count_of_b
4/2/2015, B,    , 345
4/3/2015, D,    , 553
4/1/2015, B, 888,
4/2/2015, A, 533,
4/2/2015, A, 432,
4/3/2015, C, 484, 334

1 个答案:

答案 0 :(得分:1)

您可以使用full outer joinunion allgroup by执行此操作:

select date, class, sum(count_of_a) as count_of_a, sum(count_of_b) as count_of_b
from ((select date, class, count_of_a, NULL as count_of_b
       from table_a
      ) union all
      (select date, class, NULL as count_of_a, count_of_b
       from table_b
      )
     ) ab
group by date, class;

此方法比full outer join有一些优势(除了coalesce()中不需要一堆from语句)。首先,它更为通用,因此当date和/或class采用NULL值时,它将起作用。此外,当类/日期组合有多个值时,它会正确添加值。