T-SQL(2005)RANK OVER(PARTITION BY)的答案是什么?

时间:2012-11-15 14:59:45

标签: tsql sql-server-2005 stored-procedures ranking

我有一个存储过程,它为前端进行分页并且工作正常。我现在需要修改该过程以按返回的20列中的四列进行分组,然后仅返回包含最低优先级的每个组中的行。所以当resort_id,卧室,厨房和签到(日期)都匹配时,只返回具有最小优先级的行。我还必须保持分页功能。 @startIndex和@upperbound是从前端传递到过程中用于分页的parms。我认为RANK OVER(PARTITION BY)就是我无法弄清楚如何将它们放在一起的答案。

SELECT I.id,
       I.resort_id,
       I.[bedrooms],
       I.[kitchen],
       I.[checkin],
       I.[priority],
       I.col_1,
       I.col_2 /* ..... (more cols) */
FROM  ( 
        SELECT  ROW_NUMBER() OVER(ORDER by checkin) AS rowNumber, 
        *
        FROM Inventory
      ) AS I  
WHERE  rowNumber >=  @startIndex
AND    rowNumber <   @upperBound
ORDER BY rowNumber

修复后的示例2:

SELECT I.resort_id,
       I.[bedrooms],
       I.[kitchen],
       I.[checkin],
       I.[priority],
       I.col_1,
       I.col_2 /* ..... (more cols) */
FROM Inventory i 
JOIN 
( 
    SELECT ROW_NUMBER() OVER(ORDER BY h.checkin) as rowNumber, MIN(h.id) as id
    FROM Inventory h
    JOIN (
        SELECT  resort_id, bedrooms, kitchen, checkin, id, MIN(priority) as priority
        FROM Inventory
        GROUP BY resort_id, bedrooms, kitchen, checkin, id
    ) h2 on h.resort_id = h2.resort_id and 
            h.bedrooms = h2.bedrooms and 
            h.kitchen = h2.kitchen and 
            h.checkin = h2.checkin and 
            h.priority = h2.priority
    GROUP BY h.resort_id, h.bedrooms, h.kitchen, h.checkin, h.priority
) AS I2 
    on i.id = i2.id
WHERE  rowNumber >=  @startIndex
AND    rowNumber <   @upperBound
ORDER BY rowNumber

1 个答案:

答案 0 :(得分:1)

我会这样做。

SELECT I.resort_id,
       I.[bedrooms],
       I.[kitchen],
       I.[checkin],
       I.[priority],
       I.col_1,
       I.col_2 /* ..... (more cols) */
FROM Inventory i 
JOIN 
( 
    SELECT ROW_NUMBER(ORDER BY Checkin) as rowNumber, MIN(id) id
    FROM Inventory h
    JOIN (
        SELECT  resort_id, bedrooms, kitchen, checkin id, MIN(priority) as priority
        FROM Inventory
        GROUP BY resort_id, bedrooms, kitchen, checkin
    ) h2 on h.resort_id = h2.resort and 
            h.bedrooms = h2.bedrooms and 
            h.kitchen = h2.kitchen and 
            h.checkin = h2.checkin and 
            h.priority = h2.priority
    GROUP BY h.resort_id, h.bedrooms, h.kitchen, h.checkin, h.priority
) AS I2 
    on i.id = i2.id
WHERE  rowNumber >=  @startIndex
AND    rowNumber <   @upperBound
ORDER BY rowNumber