我很难从两个表中选择数据。 我尝试使用每个连接但无法弄清楚。 我正在使用 PostgreSQL
这些是我的表格: 表_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
最佳答案
您可以使用完全外部联接
或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;
与全外连接
相比,此方法有几个优点(除了在 from
中不需要一堆 coalesce()
语句之外).首先,它更通用,所以当 date
和/或 class
取 NULL
值时它会起作用。此外,当类/日期组合有多个值时,它会正确添加值。
关于sql - 从一个表中选择所有内容,从另一个表中选择一些关于 SQL joining on 2 variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619117/