OVER Order Case基于自定义列和不同的数据类型

时间:2013-01-16 11:30:58

标签: sql stored-procedures

我有一个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,因为[Col3]的数据类型不同于theColumnName其他colums。

现在这样可以正常工作,但由于我刚刚收到错误消息Invalid column name 'theColumnName',我无法找到如何按我的专栏WHEN @sortBy = 'type4' THEN theColumnName 订购。

WHEN @sortBy = 'type4' THEN 5

我甚至尝试使用列号,例如{{1}}但这也无效。

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

1 个答案:

答案 0 :(得分: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