sql - 从一个表中选择所有内容,从另一个表中选择一些关于 SQL joining on 2 variables

标签 sql postgresql querying

我很难从两个表中选择数据。 我尝试使用每个连接但无法弄清楚。 我正在使用 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 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;

全外连接相比,此方法有几个优点(除了在 from 中不需要一堆 coalesce() 语句之外).首先,它更通用,所以当 date 和/或 classNULL 值时它会起作用。此外,当类/日期组合有多个值时,它会正确添加值。

关于sql - 从一个表中选择所有内容,从另一个表中选择一些关于 SQL joining on 2 variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31619117/

相关文章:

mongodb - 使用 Mongo 查询数组元素

php - 使用 php 使用两个查询在文章页面上创建面包屑

mysql - 如何检查修改定义

sql - 将数字列表分成大致相等的总数

spring - 如何在 spring boot/postgresql 应用程序中检查长时间运行的查询?

mysql - SQL LOWER 函数不适用于加密

sql - <column> 在两个表之间的列比较中不明确

java - 组织.postgresql.util.PSQLException : ERROR: value too long for type character varying(255)

php - 多个插入到一个表和多对多表

java - 如何在 Lucene 中查询 ">"、 "<"和 "<>"