Link to home
Start Free TrialLog in
Avatar of gvamsimba
gvamsimbaFlag for United Kingdom of Great Britain and Northern Ireland

asked on

SQL Server Self Joins

Hi,

I have a table called Test with columns questionid,text,qid

basically qid also a questionid which is a help text for the main question. questions
which does not have help text will have qid as NULL

now i want to retrive all questionid's with the question text but those questions which has
qid I want that text for qid in the same row . so basically I want the question text and the  qid
text (help text) in the same row for each questionid. for those questions where qid is null should return null. and I dont want the qid questionid's appearing as seperate questions in my result sets.

Example

questinid   text                         qid
101         what is ur name ?     102
102         this is mandatory       null
103         DOB                             null

so my result set should be like below :

questionid   text                        helptext
101          What is ur name ?    this is mandatory
103          DOB                           null



can some one please advise me the best query for this ?

Many Thanks
ASKER CERTIFIED SOLUTION
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gvamsimba

ASKER

Hi John , your join condition on t3 is incorrect. the below will work...


SELECT      T1.questinid
,      T1.text
,      T2.text helptext
FROM      Test T1
LEFT
JOIN      Test T2                  ON      T1.qid = T2.questinid
LEFT
JOIN      Test T3                  ON      T1.questinid = T3.qid
WHERE      T3.questinid IS NULL
Excellent