oracle中选出某个字段里面最大值的记录的sql语句怎么写?

时间:2022-05-08 00:36:14
我这样写的
sql = "select top 1 testfld from test_table  where ... order by testfld DESC"
用access测试地时候是正确地,可是换到oracle下面就选不出来了。在oracle下面地
这个sql语句改怎么写?
谢谢

6 个解决方案

#1


2种写法:
select max(testfld) from test_table;

select testfld from test_table
 where rownum = 1
 order by testfld desc;

一般只用第一种就行了。

#2


Oracle好像不支持 Top N 语法. 你怎么不用MAX()函数?

select max(testfld) from test_table where ...

#3


同意:
KingSunSha(弱水三千) 

得两种写法!
还有一种

select testfle from test_table where rowid in(select testfld from test_table where rownum=1 order by testfld desc;)

不过你还是用: KingSunSha(弱水三千) 第一中方法比较好!
:)

#4


感谢诸位地帮助。例外我还想问一下,关于oracle网上有没有什么好的教程。
特别是这些个特定于oracle地sql语句地写法地教程。哪里有地?多谢了~~

#5


TO:KingSunSha(弱水三千)
你的第二种方法有误,因为ROWNUM是物理位置,ORDER BY 对他不起作用。

#6


To: JAC(岛主)
多谢您指正. 我仔细查了一下ROWNUM的用法,发现ROWNUM不能和ORDER BY一起这么用. 不过ROWNUM不是物理位置, ROWID才是的.
    Oracle assigns a ROWNUM value to each row as it is retrieved, before 
    rows are sorted for an ORDER BY clause, so an ORDER BY clause 
    normally does not affect the ROWNUM of each row.  However, if an 
    ORDER BY clause causes Oracle to use an index to access the data, 

    Oracle may retrieve the rows in a different order than without the 
    index, so the ROWNUMs may be different than without the ORDER BY 
    clause. 


#1


2种写法:
select max(testfld) from test_table;

select testfld from test_table
 where rownum = 1
 order by testfld desc;

一般只用第一种就行了。

#2


Oracle好像不支持 Top N 语法. 你怎么不用MAX()函数?

select max(testfld) from test_table where ...

#3


同意:
KingSunSha(弱水三千) 

得两种写法!
还有一种

select testfle from test_table where rowid in(select testfld from test_table where rownum=1 order by testfld desc;)

不过你还是用: KingSunSha(弱水三千) 第一中方法比较好!
:)

#4


感谢诸位地帮助。例外我还想问一下,关于oracle网上有没有什么好的教程。
特别是这些个特定于oracle地sql语句地写法地教程。哪里有地?多谢了~~

#5


TO:KingSunSha(弱水三千)
你的第二种方法有误,因为ROWNUM是物理位置,ORDER BY 对他不起作用。

#6


To: JAC(岛主)
多谢您指正. 我仔细查了一下ROWNUM的用法,发现ROWNUM不能和ORDER BY一起这么用. 不过ROWNUM不是物理位置, ROWID才是的.
    Oracle assigns a ROWNUM value to each row as it is retrieved, before 
    rows are sorted for an ORDER BY clause, so an ORDER BY clause 
    normally does not affect the ROWNUM of each row.  However, if an 
    ORDER BY clause causes Oracle to use an index to access the data, 

    Oracle may retrieve the rows in a different order than without the 
    index, so the ROWNUMs may be different than without the ORDER BY 
    clause.