0

I have the following query:

SELECT X.ID, X.NAME, CASE R.ID WHEN NOT NULL THEN 1 ELSE 0 END ISRELATED
FROM TABLE X
INNER JOIN RELATIVE R ON R.NAMEID = X.ID

I'm trying to get results look like this structure, and not pull any duplicate rows from table X:

ID
NAME
ISRELATED (boolean)

Any suggestions? Thanks.

3
  • Well i changed the case statement in this example to help illustrate the need better, but currently returning duplicates with all the same value for the related column, like all ones or zeros Dec 25, 2011 at 4:34
  • just add DISTINCT to your statement Dec 25, 2011 at 4:39
  • I don't know how to do the CASE statement for this and which type of JOIN to use. WHEN IS NOT NULL doesn't work. Dec 25, 2011 at 4:41

3 Answers 3

2

Using INNER JOIN will return only those rows from X which have a corresponding row in R. Use Left outer join instead.

SELECT DISTINCT X.ID, X.NAME, CASE WHEN R.ID IS NOT NULL THEN 1 ELSE 0 END ISRELATED 
FROM TABLE X 
LEFT OUTER JOIN RELATIVE R ON R.NAMEID = X.ID 
0
0

try this

SELECT DISTINCT X.ID, X.NAME, CASE WHEN R.ID IS NOT NULL THEN 1 ELSE 0 END ISRELATED 
FROM TABLE X 
INNER JOIN RELATIVE R ON R.NAMEID = X.ID 
2
  • that returns all 1's for ISRELATED and doesn't show the 0 ones. Dec 25, 2011 at 4:43
  • maybe you need to explain what exactly you are expecting, but my guess is since you are using INNER join it will only return the ones with existing records in the RELATIVE table, might want to try LEFT OUTER join Dec 25, 2011 at 4:48
0

I think that you has an error in CASE and have to use LEFT JOIN

SELECT DISTINCT
    X.ID, 
    X.NAME, 
    CASE WHEN R.ID IS NOT NULL THEN 1 ELSE 0 END ISRELATED 
FROM TABLE X 
LEFT JOIN RELATIVE R ON R.NAMEID = X.ID 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.