代码之家  ›  专栏  ›  技术社区  ›  ilhan

如何对PostgresQL中两个不同查询的结果求和

  •  0
  • ilhan  · 技术社区  · 5 年前

    我有两个不同但相似的问题,如

    select id, name, count(*) from tb_2020_01 inner join … inner join tb2_2020_01 … inner join group by count(*) … (there is no order)
    
    id  name  count
    1   One   111
    2   Two   222
    5   Five  555
    

    然后

    select id, name, count(*) from tb_2020_02 inner join … inner join tb2_2020_02 … inner join group by count(*) … (there is no order)
    
    id name  count
    1  One   100
    3  Three 333
    

    id name  count
    1  One   211
    2  Two   222
    3  Three 333
    5  Five  555
    

    1 回复  |  直到 5 年前
        1
  •  1
  •   Nava Bogatee    5 年前

    UNION运算符用于组合两个或多个SELECT语句的结果集。

    • UNION中的每个SELECT语句必须具有相同的列数
    • 列还必须具有类似的数据类型

    看见 日期: W3Schools

    select id, name, count(*) from tb_2020_01
    UNION ALL
    select id, name, count(*) from tb_2020_02
    ...
    
        2
  •  0
  •   ilhan    5 年前
    select x."id", x."name", sum(x."count") from
    (
    
    select id, name, count(*) from tb_2020_01 inner join … inner join tb2_2020_01 … inner join group by count(*) … (there is no order)
    
    UNION ALL
    
    select id, name, count(*) from tb_2020_02 inner join … inner join tb2_2020_02 … inner join group by count(*) … (there is no order)
    
    ) x group by x."id", x."name"