Skip to content
Advertisement

How do you put a conditional statement inside of a SQL count?

I have some entries where the join date and transaction dates are the same, so I want to include a condition excluding if the count is zero (divide by zero case). I was wondering if I could include it within the COUNT statement.

I’ve tried the below and other slight variations attempting to include a conditional.

Here is a small segment of my code:

SELECT 
...
    d.revenue / COUNT((DATEDIFF(day, c.join_date, d.transaction_dates)) <= 90)
...

As explained above, this is the error:

Invalid operation: Divide by zero

Advertisement

Answer

Try to keep this syntax. Your query is incorrect after your first then.

   CASE
        WHEN condition1 THEN result1
        WHEN condition2 THEN result2
        WHEN conditionN THEN resultN
        ELSE result
    END;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement