在SQL的表news中 如何按照time的倒序排序然后查找他的第三行数据

SQL的子查询中不能有ORDER BY 所以之类的回答就不要了

第1个回答  2012-07-26
select * from news where time =
(select max(time) from news where time not in
(select max(time) from news where not in
(select max(time) from news)
)
)
and not in
(select max(time) from news)
);
利用not in反复嵌套 思路在这 自己看吧 我不知到你的表结构时怎样的 凭感觉写的(我理解的是time是news的一列 注意:时间时可以排大小的 越往前(过去得越久)的时间越小)

因为不知道你的完整程序是要做什么 所以有些限制 对于不好用一条sql语句解决的问题 可以试一下用匿名块 或者函数 存储过程 或者游标来做一下 很多时候会方便很多追问

。。。
那我要是用这种方法是不要查找倒数底第五个数据 就要嵌套4次。。。

追答

我不知道你这个具体找出来时用在哪里对于这个可以直接定义一个包 里面定义函数 或者 存储过程 由于我不知道你的time和news具体的情况 我给你一段我写的代码吧 实现的功能是: 找出哪些人时所在部门中工资降序第5名(这个5你可以稍微改一下代码做一个函数 传参就好 思路是一样的) 我这个有一张表 员工表 有部门号 员工号 工资等列

declare
type emp_department_id_table_type is table of employees.department_id%type index by binary_integer;
type emp_table_type is table of employees%rowtype index by binary_integer;
emp_department_id_table emp_department_id_table_type;
emp_table emp_table_type;
n int;
x int :=5;
begin
select distinct department_id bulk collect into emp_department_id_table from employees order by
department_id;
for i in 1..emp_department_id_table.count loop
select * bulk collect into emp_table from employees where department_id=emp_department_id_table(i) order by salary desc ;
n := emp_table.count;
case
when n>=x then
dbms_output.put_line(emp_table(x).department_id||' '||emp_table(x).first_name||' '||emp_table(x).salary);
when n>0 then
dbms_output.put_line(emp_table(n).department_id||' '||emp_table(n).first_name||' '||emp_table(n).salary);
else
null;
end case;
end loop;

end;
/

第2个回答  2012-07-26
不用order by咋排序啊,你要是只找倒数第三行的数据倒是可以
select * from table where time=(
select top (select COUNT(1)-2 from table) MAX(time) from table)追问

top 后面必须是一个整数啊
你的是一张表。。。

追答

你仔细看好,有括号的
top (select COUNT(1)-2 from table)
里面一个子查询,查出总数量-2,这样你就能得到倒数第三条之前的所有记录
然后再去time的最大值也就是最后一条,就是你要的了

追问

那newstype 和 newstime都是news中的两列
我想查找newstype=23 并且按照newstime降序排列 的第三个数据能查找吗??

追答

select * from news where time=(
select top (select COUNT(1)-2 from news) MAX(time) from news where newstype=23)
你运行看看喽

追问

我这样搜索出来的是newstype=23的最后一条数据
不是倒数第三条。。。
大神 帮帮忙吧!!

追答

额。。失误了。。还得再嵌套一次
select * from news where time=(
select max(time) from(select top (select COUNT(1)-2 from news ) time from news where newstype=23)a)

本回答被提问者采纳
第3个回答  2012-07-26
select top 1 * from 表名 where id not in (select top 2 id from 表名 order by 时间列 desc) order by 时间列 desc
id是你的主键列(或者说是唯一值的列)。
你的倒序没太理解,desc不对的话换成asc,

好吧,我的回答作废,虚心求教不用order by 的排序!追问

子查询中不是不能使用 order by 排序的吗??
只能在最后使用

追答

谁教你的啊?放心用,没问题

追问

。。真的不行

本回答被网友采纳
第4个回答  2012-07-26
你这个问题,一个sql语句是没办法做到的。
必须先order by,然后通过first 3 取出前三行,最后再取最后的一行。
第5个回答  2012-07-27
没看懂
个人感觉子查询可以使用ORDER BY语句追问

......
额 可以试一下 真的不可以

追答

只要在嵌套的子查询语句中加入 top 999 就可以了
select * from xx where xx in (
select top 999 xx from xx where xx=xx order by xx
)

相似回答