sunnky
sunnky

Reputation: 175

How to select the total count?

I have the following two tables (postgresql)

tableA

a b
----------
1 A
2 B

table B

c b
----------
1 A
3 B

I want to find out the same number of columns b, but if column a and column c are the same, count one. So the final result should be

b count
----------
A 1
B 2

How should I write sql?

Upvotes: 0

Views: 53

Answers (2)

forpas
forpas

Reputation: 164069

You need union all for the 2 tables and then group by b to count distinct values of a:

select t.b, count(distinct t.a) counter
from (select * from tablea union all select * from tableb) t
group by t.b

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520958

Aggregate by column b and take the distinct count of column a:

SELECT b, COUNT(DISTINCT a) AS count
FROM yourTable
GROUP BY b
ORDER BY b;

Upvotes: 0

Related Questions