简体   繁体   中英

How to get all category with their sum of products using their attribute in mysql

I want to get all category with sum of their products using status. If some of category have no product then show 0. My category table is

------------------------
id     |  category     |
------------------------
1      | Apple         |
2      | Samsung       |

My product Table is

----------------------------------------
id     |Name     |category_id|is_half
----------------------------------------
1      |iphone 4s|1          |1
2      |iphone 5s|1          |0
3      |iphone 6 |1          |1

I want to get if product is_half = 1 then sum using 0.5 else 1 .The result is

--------------------------------
id     |  category     |total
--------------------------------
1      | Apple         |2
2      | Samsung       |0

I try with this query, but bad luck

select c.id, c.name, sum(case when p.is_half then 0.5 else 1 end) as total
from category c left join products p
on p.category_id = c.id
group by c.id

Currently, it sums 1 even if there is no products. Add another WHEN to avoid that.

SELECT 
    c.id, 
    c.category, 
    SUM(
      CASE WHEN p.id IS NULL THEN 0 
           WHEN p.is_half THEN 0.5 ELSE 1 END
    ) 
    AS total 
FROM 
    category c 
    LEFT JOIN 
      products p 
      ON 
      p.category_id = c.id GROUP BY c.id

Also, you selected c.name , which is not valid field name. I changed it to c.category .

OUTPUT

--------------------------------
id     |  category     |total
--------------------------------
1      | Apple         |2
2      | Samsung       |0

See SQL Fiddle

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