ilhan
ilhan

Reputation: 8995

How to sum results from 2 diffrent queries in PostgresQL

I have 2 different but similar queries like

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

and then

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

I want to sum results from both of these queries like

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

How I can achieve this?

Upvotes: 3

Views: 2711

Answers (2)

ilhan
ilhan

Reputation: 8995

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"

Upvotes: 1

Nava Bogatee
Nava Bogatee

Reputation: 1765

The UNION operator is used to combine the result-set of two or more SELECT statements.

  • Each SELECT statement within UNION must have the same number of columns
  • The columns must also have similar data types
  • The columns in each SELECT statement must also be in the same order

See SQL UNION on : W3Schools

select id, name, count(*) from tb_2020_01
UNION ALL
select id, name, count(*) from tb_2020_02
...

Upvotes: 1

Related Questions