选择Distinct Sum SQL Server

时间:2011-12-17 08:20:14

标签: sql-server

我有一个SUM(tblReview.GradePoint)的问题我得到了6个GroupID Ballon的结果,因为我有三个产品有GroupID Ballon,但我希望结果为2,因为只有一个带有该groupID的评论tblReview,我该怎么做?

SELECT      Product.GroupID,
            max(Product.ProductID) as ProductID,
            max (Product.BrandID) as BrandID,
            max (Product.Year) as Year,
            max (Product.Name) as Name,
            max (tblBrand.BrandName)as BrandName,
            SUM(tblReview.GradePoint) as GradePoint

FROM        Product INNER JOIN
            tblBrand ON Product.BrandID = tblBrand.BrandID LEFT OUTER JOIN
            tblReview ON Product.GroupID = tblReview.GroupID

GROUP BY Product.GroupID


HAVING COUNT(distinct Product.GroupID) = 1

ORDER BY GradePoint DESC

Product
ProductID   GroupID     BrandID
--------------------------------------
 1          Ballon      10
 2          Ballon      10
 3          Ballon      10
 4          Ball        21
 5          Ball        21
 6          Chess       2
 7          Chess       2
 8          Hat         30


tblReview    
ProductID   GroupID     GradePoint
------------------------------------------
 2           Ballon     2
 4           Ball       1
 5           Ball       1
 5           Ball       1
 6           Chess      -1
 8           Hat        1


tblBrand    
BrandID     ProductID
-----------------------
 10         1
 10         2
 10         3
 21         4
 21         5
 2          6
 2          7
 30         8

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT      Product.GroupID,
            max(Product.ProductID) as ProductID,
            max (Product.BrandID) as BrandID,
            max (Product.Year) as Year,
            max (Product.Name) as Name,
            max (tblBrand.BrandName)as BrandName,
            max(tblReview.GradePoint) as GradePoint

FROM        Product INNER JOIN
            tblBrand ON Product.BrandID = tblBrand.BrandID LEFT OUTER JOIN
            (SELECT GroupID, SUM(GradePoint) GradePoint FROM tblReview GROUP BY GroupID) tblReview ON Product.GroupID = tblReview.GroupID

GROUP BY Product.GroupID