Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
query for read matched ,unmatched and newly added records from two tables.

SQL
--Table1
District	Center		  s_No
Chittoor	VenkatagiriKota   20004
Hyderabad	CivilSupply	  20005 
Ananthapur	NGOHome 	  20006	
Ananthapur	Ananthapur        20007
Chittoor	Chittoor          20008
Ananthapur	NGOHome 	  20010	
Ananthapur	Ananthapur        20020

SQL
--Tble2
Id       S_No	
101	 20004
102      20005
103      20006 
104	 20007
105      20008

SQL
--table3
id	s_No	Name
101	20004	aaa
104	20007	bbb
107	20010   xxx
108	20020	yyy

SQL
--O/P;
District      Center              S_No         Id      Status                        
Chittoor      VenkatagiriKota     20004	       101     Matched
Hyderabad     CivilSupply	  20005	       102     Un_matched
Ananthapur    NGOHome		  20006	       103     un_matched 
Ananthapur    Ananthapur          20007        104     Matched
Chittoor      Chittoor 	          20008	       105     Un_matched
Ananthapur    NGOHome             20010        107     Newly added
                                  20020        108     Newly added

Matched means:if Table2 and Table3 record is matched status in matched
Unmatched means:if Table2 and Table3 record is unmatched status in unmatched
Newly added:if new record is added in table3 status is newly added.
Posted
Updated 12-Jun-13 21:44pm
v2
Comments
E.F. Nijboer 13-Jun-13 4:06am    
You have all the condition defined and now you only need to hire someone with sql skills...
What have you tried yourself? Have some sql you tried?

Try below query..............please Let me know if this helps.

SQL
with cte as (select t1.District,t1.Center,t3.s_No,t3.id,case isnull(t2.id,0) when 0 then 'Newly added' else 'Matched' end as status
from Table_2 t2 right outer join Table_3 t3 on t2.S_No = t3.s_No
inner join Table_1 t1 on t3.S_No = t1.s_No)

select t1.District,t1.Center,t1.s_No,isnull(cte.status,'Un_matched') as Status from Table_1 t1 left outer join cte on t1.s_No = cte.s_No
 
Share this answer
 
Please try this...
Select table1.District,table1.Center,table1.S_No ,
		Case when (table1.s_no = table2.s_no AND table2.s_no = table3.s_no ) then 'Matched'
		When (table2.s_no Is NULL AND table3.s_no IS NULL ) then 'Newly added'
		Else 'Un_matched'		 
	End as Status
  from 
		table1 Left join
		table2  on  table2.s_no = table1.s_no
		left join table3 on table2.s_no = table3.s_no
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900