I have 3 tables;
- idmaster
- data1
- data2
idmaster
has every id. I need to count how many times each id exists in both data1 and data2 and output them seperate.
id
comes from idmaster
. Ideally would like to have all of them, even if no data exists, but thats not as important.
data1
and data2
do have id columns.
Example
id | data1 cnt | data2 cnt |
---|---|---|
A | 104 | 20 |
B | 12 | 4 |
C | 0 | 0 |
I tried this, but it gives me some nonsense numbers, data1 and data2 had the exact same number which doesnt match up to my data.
SELECT idmaster.id, count(data1.*), count(data2.*) FROM idmaster, data1, data2
WHERE idmaster.id = public.data1.id
AND idmaster.id = public.data2.id
GROUP BY idmaster.id
Results:
id | data1 cnt | data2 cnt |
---|---|---|
A | 160 | 160 |
B | 66 | 66 |
C | 7 | 7 |
I’m expecting something like this:
Example
id | data1 cnt | data2 cnt |
---|---|---|
A | 104 | 20 |
B | 12 | 4 |
C | 0 | 0 |
2
Answers
You could use
left join
to find the counts of ids separately in data1, data2 tables, then join this two separate queries to get the desired output.See a demo.
You can use two "scalar subqueries" (line #2 and #3 below) to compute the count of related rows. For example: