如何在oracle中使用row_number()?

ujv3wf0j  于 2023-03-29  发布在  Oracle
关注(0)|答案(2)|浏览(150)

我有这样的疑问:

select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RNO, my_table) AS subQuery

我想用spark jdbc连接到2个数据库- Postgres和Oracle。当我将此查询插入到dtable选项时,对于Postgres它可以工作,但对于Oracle我得到Caused by: OracleDatabaseException: ORA-00923: FROM keyword not found where expected
通过阅读oracle文档,我看到他们支持row_number,但我不明白我做错了什么。

val reader = spark.read
      .format("jdbc")
      .option("url", "location")
      .option("dbtable", ("select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RNO, my_table) AS subQuery")
))....
bsxbgnwa

bsxbgnwa1#

在Oracle中,FROM子句在SELECT语句中是强制性的,所以你不能使用(SELECT NULL),你也可以只使用NULL

SELECT ROW_NUMBER() OVER(ORDER BY NULL) AS RNO,
       my_table AS subQuery
FROM   some_table

(SELECT NULL FROM DUAL)

SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL FROM DUAL)) AS RNO,
       my_table AS subQuery
FROM   some_table

然而,后者似乎毫无意义,并且在PostgreSQL上不起作用,因为它没有DUAL表。您可以在PostgreSQL中创建一个单行只读DUAL表,但第一个选项在两个RDBMS中都有效,因此似乎有点矫枉过正。

  • 注意:您的查询在两个数据库中都是语法无效的,因为您在my_table之后有一个额外的)。*

Oracle fiddlePostgreSQL fiddle

gpnt7bae

gpnt7bae2#

在Oracle中,省略ORDER BY中的select

SQL> select row_number() over (order by null) as rno from dual;

       RNO
----------
         1

但是,您不能省略order by子句:

SQL> select row_number() over () as rno from dual;
select row_number() over () as rno from dual
       *
ERROR at line 1:
ORA-30485: missing ORDER BY expression in the window specification

SQL>

相关问题