2014-02-06 49 views
0
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 '%'[email protected]+'%') 
     AND 
     (P.[Status]=1 AND P.IsVerified = 1); 

我想添加WHERE RatingRank<5。有没有可能没有这个子查询?对于直接的问题抱歉。我应该在哪里添加此条件在分区中声明的条件

回答

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 '%'[email protected]+'%') 
      AND 
      (P.[Status]=1 AND P.IsVerified = 1) 
)x WHERE RatingRank<5;