SQL选择Distinct满足2个条件的项目数

时间:2010-12-06 09:59:27

标签: sql count group-by distinct

我正在努力让DISTINCT COUNT使用SQL DISTINCT SELECT

我不确定我是否应该在这里使用distinct,但我使用子查询得到了正确的结果,尽管这是非常重的处理方式。

这个查询做了我最终想要的结果(没有权重)

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个条件的答案。

谢谢,

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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