带有连接的派生表中的ROW_NUMBER()不是连续的?

时间:2010-11-27 00:10:15

标签: tsql sql-server-2008

我有一个包含连接数的派生表,我正在尝试实现分页,但ROW_NUMBER()不是顺序的。我想我知道为什么它不是顺序的,但有没有办法强迫它顺序?

SELECT [Results].[Row1],
       [Results].[Row2],
       [Results].[Row3],
  FROM (
    SELECT [p].[Row1],
           [p].[Row2],
           [p].[Row3],
           ROW_NUMBER() OVER (ORDER BY [p].[Id]) As RowNumber
    FROM Table1 As [l]
    JOIN Table2 As [p] ON [l].[fId] = [p].[Id]
    JOIN Users As [u] ON [p].[fId] = [u].[Id]
    JOIN Questions As [q] ON [p].[Id] = [q].[fId]) As Results

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

为什么不在最后做一个ORDER BY Results.RowNumber

答案 1 :(得分:1)

    with tempTable as (
    SELECT [Results].[Row1],
           [Results].[Row2],
           [Results].[Row3],
      FROM (
        SELECT [p].[Row1],
               [p].[Row2],
               [p].[Row3],
        FROM Table1 As [l]
        JOIN Table2 As [p] ON [l].[fId] = [p].[Id]
        JOIN Users As [u] ON [p].[fId] = [u].[Id]
        JOIN Questions As [q] ON [p].[Id] = [q].[fId]) As Results

    ) select ROW_NUMBER() OVER (ORDER BY something) As RowNumber, * from tempTable