sql排序、oracle的rownum相关。

10:15


数据库中,一个agentcode可能对应着多个enddate,这儿需要取出排序后最顶上一个。

我的想法是将所有enddate用

select enddate from t_agreement where agentcode = "00000001";

来取出来存放到一个List中,然后试用String的replace方法将其中的"/"字符去掉。再用快排将其进行排序,之后取第一个,加上"/"。完成。


龙哥的说法是,你直接在sql取的时候就排好不就好了啊。。。

select max(enddate) from t_agreement where agentcode = "000000001";


就这样。

还是对sql理解不够深刻。。


14:50


t_orcl

id type
11 a
3 b
2 c
6 d
5 e
8 f

上述表中按 id 排序后取出第三行元素。


首先我们要做的是按 id 排序。

select * from t_orcl order by id;


接下来,为了保证rownum顺序是正确的,我们只能嵌套一层select:

select id, type, rownum rn from (select * from t_orcl order by id);


这样我们得到了这样一张表:

id type rn
2 c 1
3 b 2
5 e 3
6 d 4
8 f 5
11 a 6


然后呢我们就可以取第三行了:

select * from (select id, type, rownum rn from (select * from t_orcl order by id)) t where t.rn = 3;


id type rn
5 e 3


就是这样,简单明了。

当然了,还有另外一种方法,呐,或许好用。

select * from (select id, type, rownum from (select * from t_orcl order by id) where rownum < 4) having id = max(id);


对了当你用这种逗比语句受到嘲讽的时候请不要甩锅给我谢谢。

你可能感兴趣的:(sql排序、oracle的rownum相关。)