SQL - COUNT用于计算数量的语句

时间:2018-01-28 04:31:30

标签: sql-server

我有一个数据库,用户可以在其中撰写对某些产品的评论。 每个产品都有一个类别。 我正在尝试做一个SELECT语句,它可以根据类别对评论的数量进行排序。我总共有6个类别的评论,但当我在做select语句时,结果最终为24。

 SELECT DISTINCT PRHYear AS 'Year',
             CategoryName AS 'Category',
             (SELECT COUNT(*) FROM Review R
                FULL JOIN Product P ON R.ProductID = P.ProductID
                FULL JOIN Category C ON P.CategoryID = C.CategoryID
                FULL JOIN ProductRankingHistory PRH ON C.CategoryID = PRH.PRHCategory
                WHERE C.CategoryName = 'T-Models') AS 'Reviews'
  FROM ProductRankingHistory PRH
  INNER JOIN
  Category C 
  ON PRH.PRHCategory = C.CategoryID

1 个答案:

答案 0 :(得分:0)

这个怎么样?而不是子查询?

SELECT PRH.PRHYear AS 'Year',
       C.CategoryName AS 'Category',
       COUNT(*) AS 'Reviews'
FROM ProductRankingHistory PRH, Category C, Product P, Review R
WHERE R.ProductID = P.ProductID AND
      P.CategoryID = C.CategoryID AND
      C.CategoryID = PRH.PRHCateogry
GROUP BY PRH.PRHYear, C.CategoryName