MySQL Aggreation查询?

cod*_*ama 2 mysql

我有以下mySQL代码:

SELECT 
      c.categoryId, 
      c.categoryName, c.categoryParent, 
      c.categoryDescription, 
      COUNT(p.productid) as totalProdsInCategory
    FROM categories as c
     LEFT JOIN normalproducts as p 
     ON c.categoryId = p.categoryid
WHERE c.categoryId = 41
    GROUP BY c.categoryId
    ORDER BY c.categoryParent ASC,  c.categoryName ASC
Run Code Online (Sandbox Code Playgroud)

我希望能够包含另一个COUNT列.但这只能算作p.state ="active"的产品.这是我的INCORRECT解决方案

SELECT 
      c.categoryId, 
      c.categoryName, c.categoryParent, 
      c.categoryDescription, 
      COUNT(p.productid) as totalProdsInCategory, 
      COUNT(q.productid) as totalActiveProdsInCategory
    FROM categories as c
     LEFT JOIN normalproducts as p 
     ON c.categoryId = p.categoryid
WHERE c.categoryId = 41
    GROUP BY c.categoryId
    ORDER BY c.categoryParent ASC,  c.categoryName ASC
Run Code Online (Sandbox Code Playgroud)

有帮助吗?我不知道从哪里开始......

Con*_*rix 5

您可以SUM (CASE WHEN p.state = "active" THEN 1 ELSE 0 END)用来获得您正在寻找的计数.

SELECT 
      c.categoryId, 
      c.categoryName, c.categoryParent, 
      c.categoryDescription, 
      COUNT(p.productid) as totalProdsInCategory, 
      SUM (CASE WHEN p.state = "active" THEN 1 ELSE 0 END) totalActiveProdsInCategory
    FROM categories as c
     LEFT JOIN normalproducts as p 
     ON c.categoryId = p.categoryid
WHERE c.categoryId = 41
    GROUP BY c.categoryId
    ORDER BY c.categoryParent ASC,  c.categoryName ASC
Run Code Online (Sandbox Code Playgroud)