我应该在哪里将这个条件添加到分区语句中

时间:2014-02-06 10:19:53

标签: sql sql-server sql-server-2008

SELECT   P.*,R.PlaceCategory,Pr.RatingAverage,
         ROW_NUMBER() OVER (PARTITION BY R.PlaceCategoryId ORDER BY Pr.RatingAverage DESC) AS RatingRank
FROM     dbo.Places AS P 
         INNER JOIN
         dbo.Cities AS C
         ON P.CityId = C.CityId
         LEFT JOIN
         (SELECT   SUM(Rat.Rating) / Count(Rat.Rating) AS RatingAverage,
                   Rat.PlaceId
          FROM     PlaceReview AS Rat
          GROUP BY PlaceId) AS Pr
         ON Pr.PlaceId = P.PlaceId
         INNER JOIN
         (SELECT   TOP 2 PlaceCategoryId,PlaceCategory
          FROM     dbo.PlaceCategory
          WHERE    [Status] = 1
          ORDER BY DisplayOrder) AS R
         ON R.PlaceCategoryId = P.PlaceCategoryId
WHERE    (P.CityId = @cityId OR C.City LIKE '%'+@cityName+'%')
         AND 
         (P.[Status]=1 AND P.IsVerified = 1);

我想添加WHERE RatingRank<5。是否有可能不使这个子查询?对不起直接问题。

1 个答案:

答案 0 :(得分:2)

在外部块中添加条件,因为它不能在同一查询中指定。

SELECT * FROM
(
    SELECT   P.*,R.PlaceCategory,Pr.RatingAverage,
             ROW_NUMBER() OVER (PARTITION BY R.PlaceCategoryId ORDER BY Pr.RatingAverage DESC) AS RatingRank
    FROM     dbo.Places AS P 
             INNER JOIN
             dbo.Cities AS C
             ON P.CityId = C.CityId
             LEFT JOIN
             (SELECT   SUM(Rat.Rating) / Count(Rat.Rating) AS RatingAverage,
                       Rat.PlaceId
              FROM     PlaceReview AS Rat
              GROUP BY PlaceId) AS Pr
             ON Pr.PlaceId = P.PlaceId
             INNER JOIN
             (SELECT   TOP 2 PlaceCategoryId,PlaceCategory
              FROM     dbo.PlaceCategory
              WHERE    [Status] = 1
              ORDER BY DisplayOrder) AS R
             ON R.PlaceCategoryId = P.PlaceCategoryId
    WHERE    (P.CityId = @cityId OR C.City LIKE '%'+@cityName+'%')
             AND 
             (P.[Status]=1 AND P.IsVerified = 1)
)x WHERE RatingRank<5;