ROW_NUMBER超过一个新列

时间:2011-08-16 09:51:48

标签: sql-server-2005 tsql sql-order-by row-number

是否可以通过row_number中的新列进行排序? 我想做这样的事情:

select text1 + text2 as NEW_TEXT, row_number over (order by NEW_TEXT) from table

但是这样的排序不起作用(我得到随机结果)。

4 个答案:

答案 0 :(得分:8)

您必须重复表达text1 + text2

select text1 + text2 as NEW_TEXT, 
row_number() over (order by text1 + text2)
from table

或者分步进行(foo可能是CTE)

SELECT
    NEW_TEXT,
    row_number() over (order by NEW_TEXT)
FROM
    (
    select text1 + text2 as NEW_TEXT from table
    ) foo

答案 1 :(得分:1)

另一种选择是将初始结果包装在子选择中,并在此子选择上应用ROW_NUMBER

SQL语句

SELECT  NEW_TEXT
        , ROW_NUMBER() OVER (ORDER BY NEW_TEXT)     
FROM    (       
            SELECT  text1 + text2 AS NEW_TEXT       
            FROM    [table]
        ) q         

测试数据

;WITH [table] (text1, text2) AS (
    SELECT '1', '1'
    UNION ALL SELECT '1', '0'
    UNION ALL SELECT '2', '2'
    UNION ALL SELECT '2', '1'
)
SELECT  NEW_TEXT
        , ROW_NUMBER() OVER (ORDER BY NEW_TEXT)     
FROM    (       
            SELECT  text1 + text2 AS NEW_TEXT       
            FROM    [table]
        ) q         

答案 2 :(得分:1)

您可以像这样使用子查询来执行此操作:

select NEW_TEXT, row_number() over (order by NEW_TEXT)
from
(
    select Text1 + Text2 as NEW_TEXT
    from TestTable
) TempTable

答案 3 :(得分:0)

select text1 + text2 as NEW_TEXT, 
row_number over (order by text1 + text2) 
from table