I have a table of people transferring between positions:
id | new_position | old_position |
---|---|---|
1 | A | B |
2 | C | B |
3 | B | D |
And so on, for several hundred rows.
I want to make a query that will return each position with the number of people that transferred into that position, and the number of people that transferred out. The result looking like:
position | in | out |
---|---|---|
A | 12 | 15 |
B | 5 | 20 |
C | 23 | 5 |
Etc.
It’s easy to get a count for either in, or out:
SELECT new_position, count(*)
FROM transfers
GROUP BY new_position
ORDER BY new_position
I don’t know how to get both into a single query though. Any suggestions?
2
Answers
You can use LATERAL
@Serg solution is very good and should be the accepted one, here is another one with simple SQL statements:
The first 2 CTE are based on your initial idea to count the positions separately, but then you can join them with a
FULL OUTER JOIN
(that is emulated with aUNION
of left and right joins). In this way, you are sure that all the positions are present.NULL
values are replaced with 0 forpos_in
andpos_out
when not present in the full join.Tested on: