简体   繁体   中英

Select count of total products as well as out of stock products from table

I have to 3 tables: product , product_to_store , store

product table
id quantity status
1   1       1
2   0       1
3   0       1
4   23      1

product_to_store table
store_id product_id
1        1
2        2
1        3
2        4

store table
id  name
1   store1
2   store2

To find total products I can run query to fetch all products in table product where status of product is enabled.

select count(*) from product where status=1

total             name
2              Store 1
2               store 2

To find total out of stock products I can run below query after joining all 3 tables and using group by store_id :

Select count(*) as outofproducts from product where quantity=0;

Result come like this:

outofproducts     name
1                Store 1
1                store 2

But I want combination of above 2 results in single query like below:

outofproducts  total  name
1              2      Store 1
1              2      store 2

You'd use conditional aggregatiopn, ie sum/count over conditions:

select
  s.name,
  sum(p.quantity > 0) as in_stock,
  sum(p.quantity = 0) as out_of_stock,
  count(*) as total
from store s
join product_to_store ps on ps.store_id = s.id
join product p on p.id = ps.product_id
group by s.name
order by s.name;

This makes use of MySQL's true = 1, false = 0. If you don't like it, replace sum(p.quantity = 0) with sum(case when p.quantity = 0 then 1 else 0 end) or count(case when p.quantity = 0 then 1 end) .

You can start query from store table so that we will get total rows as store table data.
Then use nested query for each store to get out of product and total product count

select 
(Select count(*) as outofproducts from product_to_store  ps inner join product p on p.id = ps.product_id where quantity=0 and ps.store_id = s.id  ) as outofproducts ,
(Select count(*) as count from product_to_store  ps inner join product p on p.id = ps.product_id where ps.store_id = s.id  ) as totalCount,
s.name
from store  s 

You could join the related subquery for count

  select t1.name, t1.outofproducts, t2.total
  from(
      select b.id, b.name , count(*) outofproducts 
      from product_to_store c  
      inner join product a on a.id = c.product_id
      inner  join store b on a.id = c.store_id 
      where a.quantity = 0
      group by  b.id, b.name 
  ) t1 
  inner join (
      select  b.id, b.name , count(*) total
      from product_to_store c 
      inner join product a on a.id = c.product_id
      inner  join store b on a.id = c.store_id 
      group by  b.id, b.name

  ) t2 on t1.id = t2.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM