为了账号安全,请及时绑定邮箱和手机立即绑定

oracle 查询数据只要排序后的第一条记录(不用rownum=1),sql语句怎么写

oracle 查询数据只要排序后的第一条记录(不用rownum=1),sql语句怎么写

繁星淼淼 2019-03-12 09:08:26
SELECT field1, field2, field3... fieldnFROM (SELECT field1, field2, field3...fieldn, ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK ) FROM tab ) tWHERE rk = 1 把这个语句嵌套到别的语句里面后select t.a,t.b,(SELECT field1, field2, field3... fieldnFROM (SELECT field1, field2, field3...fieldn, ROW_NUMBER() OVER(ORDER BY field1 DESC) AS RK ) FROM tab where field1=t.a) tWHERE rk = 1) from lkk t;会报错 ora-00904 where field1=t.a) "T"."A"请教高手怎么改
查看完整描述

4 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

假设排序的字段名字为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



查看完整回答
反对 回复 2019-03-20
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

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)


查看完整回答
反对 回复 2019-03-20
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

先在 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


查看完整回答
反对 回复 2019-03-20
  • 4 回答
  • 0 关注
  • 1711 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信