如何根据打开和关闭日期从SQL获取唯一行

时间:2010-09-28 12:00:23

标签: sql-server tsql

我有两个表,这是一个数据:

ID          ANS_ID       USER_ID  Date_Opened
06146723    858735205    55258    2009-02-20 12:59:47.0000000
06146723    481768765    55258    2009-09-16 17:04:22.0000000

和表2:

ID          ANS_ID     USER_ID  Date_Closed
06146723    630993597  5258     2009-04-02 14:35:23.0000000
06146723    1348252927 5258     2010-05-24 16:03:33.0000000

我需要将它们组合起来并获得一条记录,每条接近和开放的关节。我试过这个:

select distinct
        a.ID
       ,a.ANS_ID
       ,a.USER_ID
       ,a.Date_Opened
       ,b.Date_Closed
       ,b.ANS_ID
 from  Table1 a inner join Table2 b on a.ID = b.ID and a.Date_Opened < b.Date_Closed
 order by a.ID, a.Date_Opened

我得到了:

  06146723  858735205    55258  2009-02-20 12:59:47.0000000 2009-04-02 14:35:23.0000000 630993597
**06146723  858735205    55258  2009-02-20 12:59:47.0000000 2010-05-24 16:03:33.00000001348252927**
  06146723  481768765    55258  2009-09-16 17:04:22.0000000 2010-05-24 16:03:33.00000001348252927

如何删除中间行?

谢谢!

1 个答案:

答案 0 :(得分:2)

;with cte as
(
select 
        a.ID
       ,a.ANS_ID AS a_ANS_ID
       ,a.USER_ID
       ,a.Date_Opened
       ,b.Date_Closed
       ,b.ANS_ID AS b_ANS_ID
       ,ROW_NUMBER() over (order by a.Date_Opened asc, b.Date_Closed asc) as rn1
       ,ROW_NUMBER() over (order by b.Date_Closed desc, a.Date_Opened desc) as rn2
 from  Table1 a inner join Table2 b on a.ID = b.ID and a.Date_Opened < b.Date_Closed
)
select ID, a_ANS_ID, USER_ID, Date_Opened, Date_Closed, b_ANS_ID
from cte
where rn1 = 1 or rn2=1
order by ID, Date_Opened