Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,
sql query for retrieving matched and unmatched records from two tables.


table1
Id Name Address Date Month Year
1 sony Hyd 10 06 2013
2 jhon Blr 5 06 2013
3 Ravi Hyd 6 06 2013

table2
id sal
2 10,000
3 20,000

O/P:
id Status Catagory Name Address Sal
1 Un_matched 0-5 sony Hyd 0
2 matched 5-10 jhon Blr 10,000
3 matched 5-10 Ravi Hyd 20,000
Posted

Hi,

Check t he following script...
SQL
SELECT T1.ID,
	CASE WHEN T2.ID IS NULL THEN 'Un_matched'
        ELSE 'matched' END 'Status',
	CASE WHEN DATEDIFF(Day,CAST(T1.Year as VARCHAR(4))+ '-' + CAST(T1.Month As VARCHAR(2))+ '-' + CAST(T1.Day As VARCHAR(2)),GETDATE())>=-5 THEN '0-5'
	     WHEN DATEDIFF(Day,CAST(T1.Year as VARCHAR(4))+ '-' + CAST(T1.Month As VARCHAR(2))+ '-' + CAST(T1.Day As VARCHAR(2)),GETDATE())<-5 THEN '5-10'
	ELSE '-' END 'Category',
        T1.Name,
        T1.Address,
        ISNULL(T2.Sal,0) 'Sal'
FROM tabl1 T1
LEFT OUTER JOIN table2 T2 On T2.id=T1.id

Regards,
GVPrabu
 
Share this answer
 
v6
Comments
jhon123 2 12-Jun-13 6:32am    
Hi,
It will shows one error message.i,e

Incorrect syntax near 'B'.Expecting Select,or '('.
gvprabu 12-Jun-13 6:37am    
Send your full error message
jhon123 2 12-Jun-13 6:39am    
error is
Incorrect syntax near 'B'.
jhon123 2 12-Jun-13 6:40am    
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near 'B'.
gvprabu 12-Jun-13 6:41am    
ok, Comment the "Category" and check. Because there is NO 'B' in this Query :-)
Hi John,

I have created tables as you mentioned in your question and added the data using following code block.

SQL
INSERT INTO Table_1 VALUES 
(1,'sony', 'Hyd','10','06','2013'), 
(2,'jhon','Blr','05','06','2013'), 
(3,'Ravi','Hyd','06','06','2013')


INSERT INTO Table_2 Values
(2,10000),
(3,20000)


Here is my query to get desired result set.

SQL
SELECT Table_1.Id,Table_1.Name, (CASE WHEN Table_2.Id IS NULL THEN 'Not Matched' ELSE 'Matched' END) As Status, 
CAST(DATEDIFF(D,(Table_1.Year+Table_1.Month+Table_1.Date) ,CONVERT(VARCHAR,GETDATE(),112)) 
- (DATEDIFF(D,(Table_1.Year+Table_1.Month+Table_1.Date) ,CONVERT(VARCHAR,GETDATE(),112)) % 5) AS VARCHAR)+'-'+
CAST(DATEDIFF(D,(Table_1.Year+Table_1.Month+Table_1.Date) ,CONVERT(VARCHAR,GETDATE(),112))
 - (DATEDIFF(D,(Table_1.Year+Table_1.Month+Table_1.Date) ,CONVERT(VARCHAR,GETDATE(),112)) % 5)+ 5 AS VARCHAR) As Category,
(CASE WHEN Table_2.Id IS NULL THEN 0 ELSE Table_2.Sal END) As Salary
FROM Table_1 LEFT JOIN Table_2 
ON Table_1.Id = Table_2.Id


I hope this helps you.

Happy coding.
 
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