2010-12-06 46 views
2

我掙扎着爬一個重複計數與SQL DISTINCT SELECTSQL選擇項目的重複計數,其中2個條件都滿足

不知道工作,如果我應該甚至可以在這裏使用不同的,但我有它正確使用子查詢,儘管這是非常繁重的處理過程。

這個查詢做什麼,我最終要的結果明智的(沒有重量)

SELECT DISTINCT 
product_brandNAME, 
product_classNAME, 
    (SELECT COUNT(productID) FROM products 
    WHERE products.product_classID = product_class.product_classID 
    AND products.product_brandID = product_brand.product_brandID) as COUNT 
FROM products 
JOIN product_brand 
JOIN product_class 
ON products.product_brandID = product_brand.product_brandID 
AND products.product_classID = product_class.product_classID 
GROUP BY productID 
ORDER BY product_brandNAME 

此靠攏,而且是更有效的,但我不能得到計數工作,它只是計數(明顯)重複計數是1

SELECT DISTINCT product_brandNAME, product_classNAME, COUNT(*) as COUNT 
FROM products 
JOIN product_brand 
JOIN product_class 
ON products.product_brandID = product_brand.product_brandID 
AND products.product_classID = product_class.product_classID 
GROUP BY productID 
ORDER BY product_brandNAME 

任何建議,我敢肯定它的小,並一直在研究的淨數小時的答案無濟於事2度的條件相匹配。

感謝,

回答

1

你試過下面的查詢

編輯

SELECT product_brandNAME 
     , product_classNAME 
     , COUNT(*) 
FROM products 
     JOIN product_brand ON products.product_brandID = product_brand.product_brandID 
     JOIN product_class ON products.product_classID = product_class.product_classID    
GROUP BY 
     product_brandNAME 
     , product_classNAME 
+0

感謝利芬,這是接近正確的,但讓我在正確的軌道上,我只是拿出| GROUP BY「的productID」 |,它的贏家,感謝這麼多,保存我噸噸:) – wingman 2010-12-06 10:11:32

0

當使用GROUP BY你不需要使用DISTINCT子句。請嘗試以下操作:

SELECT productID, 
     product_brandNAME, 
     product_classNAME, 
     COUNT(*) as COUNT 
    FROM products JOIN product_brand ON products.product_brandID = product_brand.product_brandID 
       JOIN product_class ON products.product_classID = product_class.product_classID  
GROUP BY productID, 
     product_brandNAME, 
     product_classNAME 
ORDER BY product_brandNAME