Sql 如何根据到期日获取唯一记录

Sql 如何根据到期日获取唯一记录,sql,sql-server-2012,Sql,Sql Server 2012,我正在尝试此查询以基于ID_B获取唯一行,但我还希望ID_B位于DueDate最近的位置,这是我正在尝试的 SELECT distinct ID_B, ID_A, Own_ID, DueDate FROM Table1 WHERE (ID_A = 6155) 我得到的结果是 我想要唯一的ID_B和最早的到期日 例如,在结果窗格中,我只需要一条ID_B=1且DueDate=2014-07-21 10:54:02.027的ID_B记录,请尝试以下操作: ;with cte as (select

我正在尝试此查询以基于ID_B获取唯一行,但我还希望ID_B位于DueDate最近的位置,这是我正在尝试的

SELECT distinct ID_B, ID_A, Own_ID, DueDate FROM  Table1 WHERE (ID_A = 6155)
我得到的结果是

我想要唯一的ID_B和最早的到期日

例如,在结果窗格中,我只需要一条ID_B=1且DueDate=2014-07-21 10:54:02.027的ID_B记录,请尝试以下操作:

;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
你可以这样写:

;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
尝试下面的查询

-- 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

必须指定要从中选择的表。它现在给了我一个空集。现在它可以工作了。谢谢,您能告诉我如何从输出中隐藏rn吗?您不应该通过我在这里发布的查询获得rn。在任何情况下,您都可以按名称指定所有列,就像我们从表中进行选择一样。非常感谢,但是每次我在我的数据集中运行你的查询时,我得到的数据集都是空的。请检查演示链接,让我知道你缺少的数据。我已经根据这里发布的示例数据编写了查询。实际上,查询需要按到期日排序。查询现在已更新