I am executing a query but for sum cases
SUM( CASE WHEN dismissal_kind = 'caught' THEN 1 ELSE 0 END )
this part of the code results into zero which causes zero division error.I am trying to not show result(not select) when
SUM( CASE WHEN dismissal_kind = 'caught' THEN 1 ELSE 0 END )
Pease help.
"""select distinct bowler as b, count(bowler)/SUM( CASE WHEN dismissal_kind = 'caught' THEN 1 ELSE 0 END ) from deliveries group by bowler; """
Advertisement
Answer
The simplest way is to remove the else 0
:
SUM( CASE WHEN dismissal_kind = 'caught' THEN 1 END )
This returns NULL
if nothing matches the condition. Dividing by NULL
produces NULL
and not an error.
For your query however, I recommend:
select bowler as b, count(*) / nullif(count(*) filter (where dismissal_kind = 'caught'), 0) from deliveries group by bowler;
nullif()
is another way to avoid division by zero. filter
is the recommended (and standard) syntax for conditional aggregation.
If you want to filter out the rows that are null
, you can include a having
clause:
select bowler as b, count(*) / nullif(count(*) filter (where dismissal_kind = 'caught'), 0) from deliveries group by bowler having count(*) filter (where dismissal_kind = 'caught') > 0;