oracle rownum transfer to t-sql row_number() over with error

oracle rownum transfer to t-sql row_number() over with error

简化的原点pl_sql是

select t.*, staff_no||'-'||rownum as pk 
from (select * from hrmmgr.posting where type not in ('X','C') order by staff_no, postingdate) t;

我尝试在 sql 服务器中将其重写为 运行 作为

select t.*, staff_no + '-' + t.rownum as pk
from (select row_number() over (order by staff_no, postingdate) as rownum, * 
from posting where type not in ('X','C') order by staff_no, postingdate) t

但是错误

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

返回。

如果我尝试添加 OFFSET,如下错误消息所示:

select t.*, staff_no + '-' + t.rownum as pk
from (select row_number() over (order by staff_no, postingdate OFFSET 0 ROWS) as rownum, * 
from posting where type not in ('X','C') order by staff_no, postingdate) t 

然后出现如下错误。

Incorrect syntax near 'ROWS'.

那么如何在 sql 服务器中将我的 plsql 重写为 运行?

子查询中的 ORDER BY 子句似乎是问题所在,SQL 服务器告诉您 ORDER BY 不能出现在子查询中,除非同时使用 [=13] =].但是,这里甚至不需要,因为您对 ROW_NUMBER 的调用已经指定了在分配行号时要使用的 ORDER BY 子句。试试这个版本:

SELECT t.*, staff_no + '-' + t.rownum AS pk
FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY staff_no, postingdate) AS rownum, * 
    FROM posting
    WHERE type NOT IN ('X', 'C')
) t;