在SQL Server中如何将ROW_Number()与子查询列一起使用?

时间:2010-03-05 21:44:56

标签: sql-server

这是我的疑问:

DECLARE @StartRow INT
DECLARE @PageSize INT
SET @StartRow = 1
SET @PageSize = 5

SELECT ContractID,Property FROM
(
    SELECT c.ContractID, 
    Property = 
    (
        SELECT TOP 1 p.Name 
        FROM Com.Property p 
        JOIN VContract.Contract2Property c2p ON c2p.PropertyID=p.PropertyID 
        WHERE c2p.ContractID=c.ContractID
    ),
    ROW_NUMBER() OVER (ORDER BY Property) as RowNum
    FROM VContract.[Contract] c
) as sub
WHERE RowNum BETWEEN @StartRow AND ((@StartRow + @PageSize) - 1)

问题是(ORDER BY Property)部分。我可以通过c.ContractID而不是Property来订购。 那么如何才能实现这一目标呢?我需要查找属性的名称,然后我希望按该名称排序。

这用于填充网站,因此分页对我很重要,因此我可以限制一次返回的记录数。

感谢您的帮助。

4 个答案:

答案 0 :(得分:5)

尝试将您的呼叫转移到ROW_NUMBER()到您的外部查询:

    SELECT ContractID, Property, ROW_NUMBER() OVER (ORDER BY Property) as RowNum FROM
    (
        SELECT c.ContractID, 
        Property = 
        (
            SELECT TOP 1 p.Name 
            FROM Com.Property p 
            JOIN VContract.Contract2Property c2p ON c2p.PropertyID=p.PropertyID 
            WHERE c2p.ContractID=c.ContractID
        ),
        FROM VContract.[Contract] c
    ) as sub

请注意,您可能必须将where子句拉出到另一层嵌套。

答案 1 :(得分:4)

我认为当使用CTE概念的子查询时,你将克服这个问题

WITH VContract AS
(
 SELECT ROW_NUMBER() OVER (ORDER BY Property) as RowNum, ContractID
 FROM
 (
   SELECT c.ContractID AS ContractID, 
     Property = 
     (
        SELECT TOP 1 p.Name 
        FROM Com.Property p 
        JOIN VContract.Contract2Property c2p ON c2p.PropertyID=p.PropertyID 
        WHERE c2p.ContractID=c.ContractID
     )    
    FROM VContract.[Contract] c
 )
)
SELECT ContractID FROM VContract 
WHERE RowNum BETWEEN @StartRow AND ((@StartRow + @PageSize) - 1)

答案 2 :(得分:1)

我没试过这个,但是......我添加了一个新的外层,它限制了行号

SELECT ContractID,Property FROM  
(
  SELECT ContractID,Property, RowNum FROM  
  (  
      SELECT c.ContractID,   
      Property =   
      (  
          SELECT TOP 1 p.Name   
          FROM Com.Property p   
          JOIN VContract.Contract2Property c2p ON c2p.PropertyID=p.PropertyID   
          WHERE c2p.ContractID=c.ContractID  
      ),  
      ROW_NUMBER() OVER (ORDER BY Property) as RowNum  
      FROM VContract.[Contract] c  
  ) as sub_inner
) as sub_outer
WHERE RowNum BETWEEN @StartRow AND ((@StartRow + @PageSize) - 1)  

答案 3 :(得分:0)

我猜测订单不起作用,因为它是一个子选择。

您可以只使用Contract进行连接以获取名称,而不是使用子选择来获取属性名称的值吗?然后你可以通过名字订购。