【问题标题】:Select everything from one table and some from anothe table on SQL joining on 2 variables从一个表中选择所有内容,从另一个表中选择一些关于 SQL 加入 2 个变量的内容
【发布时间】:2015-10-15 15:11:45
【问题描述】:

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

【问题讨论】:

  • 提示:完全外连接。

标签: sql postgresql querying


【解决方案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 相比,此方法有几个优点(除了不需要from 中的一堆coalesce() 语句)。首先,它更通用,因此当date 和/或class 采用NULL 值时它会起作用。此外,当类/日期组合有多个值时,它会正确添加值。

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 1970-01-01
    • 2021-07-09
    • 2011-03-30
    • 1970-01-01
    • 2023-03-24
    • 2021-12-30
    • 2022-12-09
    • 2013-12-23
    相关资源
    最近更新 更多