Oracle选择查询来过滤行

时间:2015-08-20 21:38:11

标签: sql oracle select oracle11g

假设我有一个包含以下值的表

id (PK) a_num  a_code effect_dt  expire_dt
32      1234   abcd   01/01/2015 05/30/2015
9       1234   abcd   06/01/2015 12/31/2015
5       1234   efgh   01/01/2015 05/30/2015
14      1234   efgh   06/01/2015 12/31/2015

如何从a_numa_code对中仅选择一条记录。 Id的1,3或2,4?可能存在a_numa_code对的记录超过2个的情况。

更新 - ID不一定总是有序,它只是一个主键。

2 个答案:

答案 0 :(得分:1)

一种方法是使用row_number窗口函数:

SELECT id, a_num, a_code, effect_dt, expire_dt
FROM   (SELECT id, a_num, a_code, effect_dt, expire_dt,
               ROW_NUMBER() OVER (PARTITION BY a_num, a_code
                                  ORDER BY 1) AS rn
        FROM   mytable) t
WHERE  rn = 1

答案 1 :(得分:1)

这将为您提供第1行和第3行

Select * from (
   Select * , Row_number() Over(Partition by a_num, a_code order by id) r_num from Your_Table ) result
Where r_num = 1

按顺序使用DESC,您将获得第2行和第4行

Select * from (
   Select * , Row_number() Over(Partition by a_num, a_code order by id desc) r_num from Your_Table ) result
Where r_num = 1