2011-12-17 166 views
1

我與SUM(tblReview.GradePoint)我得到6的結果爲羣ID金球獎,因爲我有三個產品羣ID巴隆一個問題,但我希望得到的結果是2,因爲只有一個在tblReview該組ID,我怎麼能做到這一點嗎?SELECT DISTINCT總和的SQL Server

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 

回答

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

完美!謝謝! – user1007103 2011-12-17 08:44:33