oracle 查询数据只要排序后的第一条记录(不用rownum=1),sql语句怎么写
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) "T"."A"请教高手怎么改 展开
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;
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
把 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
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) ;