1、创建测试表羡者,
create table test_order(id number, value varchar2(50));
2、插入测试数据
insert into test_order values(3,'v3');
insert into test_order values(2,'v2');
insert into test_order values(1,'v1');
insert into test_order values(5,'v5');
insert into test_order values(4,'v4');
commit;
3、查询表中全量数据,可以发现侍雹数据并未排序,select t.*, rowid from test_order t;
4、编写sql,数据只要排兄谈薯序后的第一条记录(不用rownum=1) select * from (select t.*, row_number() over(order by id) rn from test_order t) t where rn = 1;
假设排序的字段名字为field1降序, table name: tab
SELECT field1, field2, field3... fieldn
FROM (SELECT field1, field2, field3...fieldn, ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK ) FROM tab ) t
WHERE rk = 1
00904是吵李说列名不正确,仔细看了下,AS RK后面多了一个括号,下面这样就可以了
SELECT field1, field2, field3... fieldn
FROM (SELECT field1, field2, field3...fieldn,
ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK
FROM tab
where field1=表名.字段名) t
WHERE rk = 1
我给你庆碰掘改一下吧,你写的那个效率很誉核低的
SELECT t1.a, t1.b, t2.field1, t2.field2, t2.field3...t2.fieldn
FROM lkk t1,
(SELECT field1, field2, field3...fieldn,
ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK
FROM tab) t
WHERE t.field1 = t1.a
AND t.rk = 1
首先在 XSREMOBILE 表上建 SENDDATE和空闷ID 的复孝败合索引.
把 WHERE ROWNUM < 50 + 1
改为 WHERE ROWNUM <= 50
应该可以快斗慎弯些.
SELECT /*+ FIRST_ROWS */ *
FROM (SELECT /*+ parallel(M,10) */ *
FROM XSREMOBILE M
WHERE M.SENDDATE >= 20101126
AND M.SENDDATE <= 20101126
oRDER BY M.ID DESC
)
WHERE ROWNUM <= 50
SELECT field1, field2, field3... fieldn
FROM (SELECT field1, field2, field3...fieldn, ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK ) FROM tab ) t
WHERE rk = 1
把这个语句告空嵌套到别的语乱祥句里哗友搏面后
select t.a,t.b,
(SELECT field1, field2, field3... fieldn
FROM (SELECT field1, field2, field3...fieldn, ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK ) FROM tab where field1=t.a) t
WHERE rk = 1)
from lkk t;
会报错 ora-00904 where field1=t.a)
如果该表有时间或数值类型字段的话可以采用如下;
SELECT *
FROM table 碧睁a
WHERE a.time = (SELECT MAX (b.time)
芦野 悔哗岁 FROM table b) ;