I have a problem with group by and count().
I need a result table looks like below.
Tried I guess all the variations of JOIN.
There are two types of wrong result:
– first when the row "3 C 0" is missing,
– the second when it is present but with a false value "3 C 1"
Table1:
id name
1 A
2 B
3 C
4 D
Table2:
id
1
1
2
1
4
result should look like this:
id name count
1 A 3
2 B 1
3 C 0
4 D 1
Any ideas?
Best Answer
Basically, you want a subquery like this:
See the fiddle here.
Basically, what I did was:
Create tables t1 and t2:
and
Populate them:
and
Ran my query:
Result:
The inner query gets the counts and then the
LEFT JOIN
causes theid1
of3
to be present - otherwise it would be missing from the result set and theCOALESCE
function (see here also) causes the value0
to be present instead ofNULL
which would otherwise be there. I initially misread the question - p.s. welcome to the forum!