lalithg


{ City }
< Country > india
* Profession *
User No # 9066
Total Questions Posted # 0
Total Answers Posted # 1

Total Answers Posted for My Questions # 0
Total Views for My Questions # 0

Users Marked my Answers as Correct # 85
Users Marked my Answers as Wrong # 69
Questions / { lalithg }
Questions Answers Category Views Company eMail




Answers / { lalithg }

Question { TCS, 56659 }

What is a self join? Explain it with an example?


Answer

CREATE TABLE candytest
(kidId char(2),
candycolor varchar(10)
)
GO

INSERT INTO candytest SELECT 'K1', 'Yellow'
INSERT INTO candytest SELECT 'K1', 'Red'
INSERT INTO candytest SELECT 'K2', 'Red'
INSERT INTO candytest SELECT 'K2', 'Blue'
INSERT INTO candytest SELECT 'K3', 'White'
INSERT INTO candytest SELECT 'K3', 'Red'
INSERT INTO candytest SELECT 'K3', 'Yellow'
Go
--Now to find those kidid's which has both yellow and red
colored candies, we can write query as:

SELECT c1.kidid
FROM candytest AS c1 JOIN candytest AS c2
ON c1.candycolor = 'Red' AND c2.candycolor = 'Yellow'
AND c1.kidid = c2.kidid

Is This Answer Correct ?    85 Yes 69 No