I have recently started using SQL and have a question.
My first query outputs all products
SELECT
COUNT(*)
FROM
products;
My second query outputs the out of stock products
SELECT
COUNT(*)
FROM
products
WHERE
qty = 0;
I want to calculate what percentage of the products are out of stock.
To to this I use this formula:
percentage = out_of_stock_products * 100 / all_products
I've tried it with this, but this doesn't worked
SELECT
(
SELECT
COUNT(*)
FROM
products
WHERE
qty = 0;
) * 100 / COUNT(*)
FROM
products;
Try this:
SELECT COUNT(CASE WHEN qty = 0 THEN 1 END) * 100.0 / COUNT(*)
FROM products
The above query uses conditional aggregation in order to calculate the number of out of stock products.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With