生成按虚拟/构造列中的值排序的行号

时间:2015-05-21 22:21:50

标签: sql-server

我正在尝试生成按构造列中的值排序的行号,但是我一直收到错误:

无效的列名称'Type'。

SELECT  ROW_NUMBER() OVER (ORDER BY [Type] ASC) As [RowID], [ID], 
   case when ([CaseOne] = 1) then 1 else case when ([Label] IS NOT NULL) then 2 else 3 end end AS [Type]
FROM [Table1]

使用2008 R2。

1 个答案:

答案 0 :(得分:2)

您需要将CASE语句放入ORDER BY。您无法在ORDER BY或HAVING子句中使用ALIASed列:

SELECT
  ROW_NUMBER() OVER ( ORDER BY CASE WHEN ( [CaseOne] = 1 ) THEN 1
                                    ELSE CASE WHEN ( [Label] IS NOT NULL )
                                              THEN 2
                                              ELSE 3
                                         END
                               END ASC ) AS [RowID],
  [ID],
  CASE WHEN ( [CaseOne] = 1 ) THEN 1
       ELSE CASE WHEN ( [Label] IS NOT NULL ) THEN 2
                 ELSE 3
            END
  END AS [Type]
FROM
  [Table1]