假设我有一个包含以下值的表
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_num
,a_code
对中仅选择一条记录。 Id的1,3或2,4?可能存在a_num
,a_code
对的记录超过2个的情况。
更新 - ID不一定总是有序,它只是一个主键。
答案 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