我很难从两张桌子中选择数据。 我尝试使用每个连接但无法弄明白。 我正在使用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
答案 0 :(得分:1)
您可以使用full outer join
或union all
和group 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
值时,它将起作用。此外,当类/日期组合有多个值时,它会正确添加值。