从表中获取3个最新详细信息

时间:2016-06-21 09:12:56

标签: sql sybase

我想为一个人提取3个最新设备。表结构如下所示

PERSON_DEVICE

person_id  seq_num   device_detail device_detail_added
999         1           Nexus        03/04/2015
999         2            iphone       06/07/2015
999         3            laptop       08/09/2015
999         4            uda           02/01/2016
999         5            pda            04/04/2016
1001        1            sm             03/03/2015 
... and so on

对于某人的最新设备,我可以使用以下查询

select * from PERSON_DEVICE
where person_id = 999
  and seq_num = (select max(seq_num) from PERSON_DEVICE where person_id = 999)

但是对于第二个最新的和第三个最新的,我不知道如何得到这个?

我尝试使用limit,但在Sybase中它不起作用(对于我的Sybase版本)。

P.S。 seq_num用于标识特定人员ID的最新设备。

******************** EDIT ************************** *************** 88

 PERSON 
person_id  name   addres
999         john   2 avenue
1001      elliot    rrt

I want to  records to 

select   pn.name , pd.device1 ,pd.device_detail_added1, pd.device2 ,pd.device_detail_added2,pd.device3 ,pd.device_detail_added3 from  PERSON pn , PERSON_DEVICE pd

3 个答案:

答案 0 :(得分:0)

如果seq_num用于获取最新使用的设备,则以下查询应该有效:

SELECT TOP 3 *
FROM PERSON_DEVICE 
WHERE person_id=999
ORDER BY seq_num DESC

答案 1 :(得分:0)

这适用于所有person_id(删除where person_id=999

select * 
  from (
        select person_id , device_detail, device_detail_added, seq_num ,
               row_number() over (partition by person_id order by seq_num desc) as rango
           from PERSON_DEVICE 
          where person_id=999) as t
where rango <=3;

答案 2 :(得分:0)

在oracle db中,您可以使用以下内容获取第三个最新版本:

SELECT * FROM (SELECT PERSON_DEVICE.*, ROW_NUMBER() OVER(ORDER BY SEQ_NUM DESC) AS TARGET_NO FROM PERSON_DEVICE WHERE PERSON_ID = 999) WHERE TARGET_NO <= 3