I am not able to get the proper count. I have 2 tables:
Tbl1
id | name | call |
---|---|---|
123 | aaaaaa | 15 |
132 | bbbbb | 0 |
Tbl2
id | involvement |
---|---|
123 | 0 |
123 | 0 |
123 | 1 |
I would like to get the count of ids where call = 15
and involvement = 0
. My query:
select t1.id,
COUNT(CASE WHEN t1.call=15 THEN 1 END) as calls
from Tbl1 t1
left join Tbl2 t2
on t2.id = t1.id
where t2.involvement = 0;
The result expected for count
is 1
.
2
Answers
group by
to work.case
statement inside an aggregate function is emulating an aggregate filter.join
have matching names, you can list them injoin...using(...)
:Tbl1
andTbl2
are actuallytbl1
andtbl2
. Some ORM’s, IDE’s and clients can be set to auto-quote. For clarity, it’s best to use the actual name the objects end up getting.Demo:
If you also want to see a list of those distinct
id
that were counted, you can use thestring_agg()
orarray_agg()
shown above.Check out Markdown help to format your questions and answers in the future.
I would prefer
exists
-based solution, because of 2 reasons:t1.id
s which must be "repaired" withdistinct
(unlessid
is not unique int1
itself – I assume it is a key)involvement = 0
suffices for counting. (If – for example – the logic had to be changed to, say, having onlyinvolvement = 0
, the condition would be easily changed toall
ornot exists
operator but core of query would stay untouched.)