Skip to content
Advertisement

SQL Server – Dsiplay all rows from LEFT table even when the condition is not met

I want to get all Titles and Scores for a Given skill Id, every skill has titles mandatorily but there may not be records in the Answer table matching the condition A.[ServiceId] = 45 in this case i still need to display all the Titles and 0 as score

 SELECT T.[Title] AS 'Title', SUM(A.[Total]) AS 'Score' FROM dbo.[Title] T
    LEFT JOIN dbo.[Answer] A
    ON T.[TitleId] = A.[TitleId]
    WHERE T.[SkillId] = 2 AND A.[TypeId] = 21
    AND A.[ServiceId] = 45
    GROUP BY T.[Title]

For this purpose i made LEFT Join and still it doesn’t display the titles, if i remove the condition A.[ServiceId] = 45 i get Titles displayed but the scores are not accurate

How do i display the titles all the times even though the condition A.[ServiceId] = 45 is not met, display 0 as score

Advertisement

Answer

Just move the conditions on the LEFT JOINed table to the ON clause of the JOIN:

SELECT T.[Title] AS 'Title', SUM(A.[Total]) AS 'Score' FROM dbo.[Title] T
LEFT JOIN dbo.[Answer] A
    ON T.[TitleId] = A.[TitleId] AND A.[TypeId] = 21 AND A.[ServiceId] = 45
WHERE T.[SkillId] = 2 
GROUP BY T.[Title]

If you put the conditions in the WHERE clause, they become mandatory, and rows where the LEFT JOIN did not match are filtered out.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement