ROWNUM作为T-SQL中的伪列等价物?

时间:2018-06-07 20:57:00

标签: sql sql-server oracle tsql plsql

当使用ROWNUM作为伪列时,如何使用T-SQL编写以下查询?这是完整的查询。我意识到它是用PL / SQL编写的,我需要更改附加对象。

BASE AS (
SELECT NULL AS ES_CMPNY_STATUS_KEY
  ,CSG.CMPNY_STATUS_GROUP
  ,CSG.CMPNY_STATUS_GROUP_ID
  ,CSG.CMPNY_STATUS_REASON
  ,CSG.CMPNY_STATUS_REASON_ID
  ,CSF.CMPNY_CURRENT_STATUS_FLAG
  ,TRUNC(SYSDATE) AS LOAD_DATE
  FROM CMPNY_STATUS_GROUP CSG
  CROSS JOIN CMPNY_CURRENT_STATUS_FLAG CSF
  ORDER BY CSG.CMPNY_STATUS_GROUP, CSG.CMPNY_STATUS_REASON

   )SELECT ROWNUM AS ES_CMPNY_STATUS_KEY
   ,CMPNY_STATUS_GROUP
   ,CMPNY_STATUS_GROUP_ID
   ,CMPNY_STATUS_REASON
   ,CMPNY_STATUS_REASON_ID
   ,CMPNY_CURRENT_STATUS_FLAG
   ,LOAD_DATE
 FROM BASE B
UNION
SELECT 0 AS ES_CMPNY_STATUS_KEY
  ,NULL AS CMPNY_STATUS_GROUP
  ,0 AS CMPNY_STATUS_GROUP_ID
  ,NULL AS CMPNY_STATUS_REASON
  ,0 AS CMPNY_STATUS_REASON_ID
  ,0 AS CMPNY_CURRENT_STATUS_FLAG
  ,TRUNC(SYSDATE) AS LOAD_DATE
  FROM DUAL

1 个答案:

答案 0 :(得分:2)

使用row_number()

select row_number() over (order by (select null)) as ES_CMPNY_STATUS_KEY

请注意,order by是必需的。实际上出现(select null)以避免任何其他排序。但是,通常,您将包含一个列,用于指定所需数据的排序顺序。