2012-03-29 228 views
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 

我希望能夠包括另算列。但是這隻能算作p.state =「active」的產品。這是我的錯誤解決方案

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 

任何幫助嗎?我不知道該從哪裏出發......

回答

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 
+0

+1比我的好,但我會離開我的 – 2012-03-29 18:04:03

1

試試這個:

SELECT 
     c.categoryId, 
     c.categoryName, c.categoryParent, 
     c.categoryDescription, 
     COUNT(p.productid) as totalProdsInCategory, 
     SUM(IF(p.state='active',1,0)) 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 

這類似於@康拉德的,但在我看來

0

這工作,但也許有點清潔不與左對齊加入方法這麼多:

SELECT   
c.catId,c.catName, 
COUNT(p.productId) as totalProdsInCategory, 
(SELECT count(*) from product as p where p.catId=1 AND p.state='active') as totalActive 
FROM cat as c  
LEFT JOIN product as p ON c.catId = p.catId 
WHERE c.catId = 1  
GROUP BY c.catId  
ORDER BY c.catName ASC