如何根据截止日期获取唯一记录

时间:2014-07-23 09:44:41

标签: sql sql-server-2012

我正在尝试此查询以获取基于ID_B的唯一行但我也想要ID_B其中DueDate最近,这就是我正在尝试的,

SELECT distinct ID_B, ID_A, Own_ID, DueDate FROM  Table1 WHERE (ID_A = 6155)

我得到的结果,

enter image description here

我想要最早的截止日期的唯一ID_B。

例如在结果窗格中,我只想要ID_B = 1的一个ID_B记录,其中DueDate = 2014-07-21 10:54:02.027

3 个答案:

答案 0 :(得分:0)

试试这个:

;with cte as
(select id_b, id_a, own_id, duedate,
 row_number() over (partition by isnull(id_b,0) order by duedate) rn
 from yourtable
 where id_a = 6155)

select id_b,id_a,own_id,duedate from cte
where rn = 1

Demo

答案 1 :(得分:0)

你可以写成:

;with CTE as 
( Select ID_B,
         ID_A,
         DueDate,        
         Row_number() over ( partition by ID_B order by [DueDate] asc) as rownum
         from Table1
 ) 
 select ID_B, ID_A,DueDate
 from CTE C
 where C.rownum = 1 and ID_A = 6155 and ISNULL(ID_B,0)<>0

Check Demo here..

答案 2 :(得分:-1)

尝试以下查询

-- create table
Create Table Table5 (ID_A int, ID_B int, Own_ID int identity, Due_date datetime)

-- insert the values into the newly created tbale
insert into Table5 values (1,100,GETDATE())
insert into Table5 values (1,100,GETDATE()+1)
insert into Table5 values (1,100,GETDATE()+2)

insert into Table5 values (1,200,GETDATE())
insert into Table5 values (1,200,GETDATE()+1)
insert into Table5 values (1,200,GETDATE()+2)

-- Query to fetch the nearest record 
Select * from 
(
Select Row_number()over( partition by ID_B order by Due_date desc) as row ,* from Table5
) as temp
where temp.row = 1