1

我有一个 SQL 语句,用于对结果进行分页ROW_NUMBER()

SELECT * FROM (
    SELECT
        ROW_NUMBER() OVER ( ORDER BY [tbl1].[Col1] ASC ) As RowNumber,
        [tbl1].[Col1],
        [tbl1].[Col2],
        [tbl1].[Col3],
        ( SELECT [tbl2].[Col1] 
          FROM [tbl2] 
          WHERE [tbl2].[id] = [tbl1].[id] 
                AND [tbl2].[subid] = 2 ) As theColumnName
    FROM
        [tbl1]
) As tbl
WHERE RowNumber BETWEEN 1 AND 10

这一切都工作正常,正如预期的那样。但是,我现在想介绍一些ORDER BY基于传递到存储过程中的值的附加功能。

所以我已将我的ROW_NUMBER() OVER (ORDER BY...声明更新为

ROW_NUMBER() OVER (ORDER BY 
    CASE WHEN @sortBy = 'type1' THEN [tbl1].[Col1]
         WHEN @sortBy = 'type2' THEN [tbl1].[Col2]
    END,
    CASE WHEN @sortBy = 'type3' THEN [tbl1].[Col3]
    END
ASC) As RowNumber

正如您在此处看到的,我CASE在方法中有一个语句OVER (),并且有两个CASE's,因为[Col3]它的数据类型与其他列不同。

现在这工作正常,但我不知道如何按我的列排序,theColumnName因为我刚刚收到错误消息Invalid column name 'theColumnName'

WHEN @sortBy = 'type4' THEN theColumnName

我什至尝试过使用列号,例如WHEN @sortBy = 'type4' THEN 5,但这也不起作用。

有没有办法按这个自定义列名排序?

4

1 回答 1

3

您需要将子查询移动到from子句中,例如:

SELECT
    ROW_NUMBER() OVER ( ORDER BY [tbl1].[Col1] ASC ) As RowNumber,
    [tbl1].[Col1],
    [tbl1].[Col2],
    [tbl1].[Col3],
    t2.col1 As theColumnName
FROM [tbl1] t join
     (select id, col1
      from tbl2
      where subid = 2
    ) t2
    on t.id = t2.id

现在,您将能够包含t2.col1在该row_number() order by子句中。

于 2013-01-16T11:39:09.187 回答