sql server - How to get unique rows from TSQL based on date open and closed -


i have 2 tables data one:

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 

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

i need combine them , 1 record, per close , open joint. tried this:

select distinct         a.id        ,a.ans_id        ,a.user_id        ,a.date_opened        ,b.date_closed        ,b.ans_id   table1 inner join table2 b on a.id = b.id , a.date_opened < b.date_closed  order a.id, a.date_opened 

and got:

  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 

how can remove middle row?

thank you!

;with cte ( select          a.id        ,a.ans_id a_ans_id        ,a.user_id        ,a.date_opened        ,b.date_closed        ,b.ans_id b_ans_id        ,row_number() on (order a.date_opened asc, b.date_closed asc) rn1        ,row_number() on (order b.date_closed desc, a.date_opened desc) rn2   table1 inner join table2 b on a.id = b.id , a.date_opened < b.date_closed ) select id, a_ans_id, user_id, date_opened, date_closed, b_ans_id cte rn1 = 1 or rn2=1 order id, date_opened 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -