Search code examples
sql-server-2014

joining two tables and avoid duplicate rows


I am stuck with below logic in sql server.

Table 1:

ID  Requestid  
1    0001       
2    0004       
3   0004        
1   0005  

Table 2

parentID  Requestid  Age
1         0001       29
2         0004       30
3         0004        34
1         0005        27

query:

select * from table1 t1
join table t2
on t2.parentid =t1.id

When I join these tables, I am getting below result

ID       requestid         age
1         0001             29
1         0005             29
2         0004             30
3         0004             34
1         0001             27
1         0005             27

I want below result:

ID       requestid         age
1         0001             29
1         0005             27
2         0004             30
3         0004             34

I know it is simple and i am missing something. Any help is appreciated!


Solution

  • select ID, requestid, age from table1 t1
    inner join table t2
    on t2.parentid =t1.id AND t2.requestId = t1.requestId
    ORDER BY ID
    

    OR

    select ID, requestid, age from table1 t1,table t2    
    where t2.parentid =t1.id AND t2.requestId = t1.requestId
    ORDER BY ID