Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine 2 SQL querys to one result?

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;
like image 584
minz Avatar asked Nov 27 '25 07:11

minz


1 Answers

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.

like image 131
Giorgos Betsos Avatar answered Nov 29 '25 21:11

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!