I have table like that:
ID NAME SURNAME MotherID FatherID 0 JJ smi NULL NULL 1 ja rly NULL NUL 2 ak smi 0 1 3 ol smi 0 1 4 oa woo 2 3 5 oe boo 2 3 etc.
I need query that with specific parameter as NAME and surname will return me all siblings of a person. Expected output
NAME SURNAME FATHERNAME FATHERSURNAME MOTHERNAME MOTHERSURNAME AK SMI JA RLY JJ SMI OL SMI JA RLY JJ SMI
I tried
SELECT a.name, a.surname FROM PEOPLE a, PEOPLE b WHERE (b.name = 'ak' AND b.surname ='smi' AND (b.motherID = a.ID OR b.fatherid = ID))
Advertisement
Answer
You can use a SUB QUERY to achieve this.
Table Creation:
DECLARE @T TABLE( ID INT, NAME VARCHAR(MAX), SURNAME VARCHAR(MAX), MOTHERID INT, FATHERID INT)
Table Insertion:
Insert into @t Values(0,'JJ','smi',NULL,NULL) Insert into @t Values(1,'ja','rly',NULL,NULl) Insert into @t Values(2,'ak','smi',0,1) Insert into @t Values(3,'ol','smi',0,1) Insert into @t Values(4,'oa','woo',2,3) Insert into @t Values(5,'oe','boo',2,3)
Query:
SELECT S.NAME AS NAME,S.SURNAME AS SURNAME,S.FATHER_NAME ,S.FATHER_SURNAME,M.NAME AS MOTHER_NAME,M.SURNAME AS MOTHER_SURNAME FROM @T M INNER JOIN( SELECT T2.NAME AS NAME,T2.SURNAME AS SURNAME,T1.NAME AS FATHER_NAME,T1.SURNAME AS FATHER_SURNAME,T2.MOTHERID FROM @T T1 INNER JOIN @T T2 ON T1.ID=T2.FATHERID WHERE T2.NAME IN ('AK','OL'))S ON M.ID=S.MOTHERID
Output:
Also ,add the WHERE clause based on your parameter requirement.