I want to find the rate of negative and zero profits from a column. I tried to do it using aggregate and subquery but it doesn’t seem to work as both method return 0 values.
The code is as follows
SELECT
COUNT(CASE WHEN profit < 0 THEN 1
END) AS negative_profits,
COUNT(CASE WHEN profit < 0 THEN 1
END) / COUNT(profit),
COUNT(CASE WHEN profit = 0 THEN 1
END) AS zero_profits,
COUNT(CASE WHEN profit = 0 THEN 1
END) / COUNT(profit)
FROM sales;
SELECT (SELECT COUNT(*)
FROM sales
WHERE profit <= 0)/COUNT(profit) AS n_negative_profit
FROM sales;
Both query return 0 in values
enter image description here
2
Answers
Because you are doing integer division per docs Math operators/functions.
So:
You need to make one of the numbers
float
ornumeric
:and to make it cleaner round:
Avoid integer division, which truncates (like Adrian pointed out).
Also, simplify with an aggregate
FILTER
expression:If
profit
is definedNOT NULL
, or to divide by the total count either way, optimize further:See: