由mysql组成的COUNT总计

时间:2016-12-21 08:08:38

标签: mysql count group-by

这个mysql查询为我提供了按天和小时分组的产品销售数量(total和total_staff)。我希望每个产品的总计总计 total_staff (不按任何方式分组,期望按ID)。我可以在同一个查询中执行此操作吗?

SELECT p.name, p.color, DATE(date_create) as jour,HOUR(date_create) AS h,
SUM(CASE WHEN s.staff=0 THEN 1 ELSE 0 END) as total,
SUM(CASE WHEN s.staff=1 THEN 1 ELSE 0 END) as total_staff
FROM manifsSubCategories msc
LEFT JOIN products_subCategories psc ON msc.id=psc.manifSubCategory_id
LEFT JOIN sales s ON psc.product_id=s.product_id
LEFT JOIN products p ON psc.product_id=p.id
LEFT JOIN manifsCategories ON manifCategory_id=manifsCategories.id
WHERE manifCategory_id=1 AND s.category_id=1 GROUP BY jour,h ORDER BY p.id DESC 

1 个答案:

答案 0 :(得分:0)

只需省略其他列:

SELECT p.name,
    SUM(CASE WHEN s.staff=0 THEN 1 ELSE 0 END) as total,
    SUM(CASE WHEN s.staff=1 THEN 1 ELSE 0 END) as total_staff
FROM manifsSubCategories msc
LEFT JOIN products_subCategories psc ON msc.id=psc.manifSubCategory_id
LEFT JOIN sales s ON psc.product_id=s.product_id 
LEFT JOIN products p ON psc.product_id=p.id
LEFT JOIN manifsCategories ON manifCategory_id=manifsCategories.id
WHERE manifCategory_id=1 AND s.category_id=1
GROUP BY p.name
ORDER BY p.id DESC

BTW - 你的WHERE条款错了。您正按照LEFT JOIN的表格进行过滤,由于inner join比较,这会将您的加入转为NULL。左边加入的右表中的条件应该只是放在ON条款中。