I am trying to write a SQL Server CASE statement to retrieve a student's category based on the following condition.
If the category
column from the student_category
table has both values 'X' and 'Y' for a student_id
value from the student
table, then only display the record where value is 'Y'.
If the category
has either values 'X' or 'Y', then display the records with that value.
If the category
does not have values 'X' or 'Y', display a blank for the column i.e. if there are any other categories except 'X' or 'Y', display a blank.
Thus, I should only have one row of data for each student_id
even if they have multiple categories. However, I am still getting multiple records for each student_id
with more than one category. Any ideas on what I might be missing ?
SELECT DISTINCT
s.student_id,
CASE
WHEN sc.category = 'X' AND sc.category = 'Y' THEN 'Y'
WHEN sc.category = 'X' OR sc.category = 'Y' THEN sc.category
ELSE ''
END AS student_cat
FROM
student s
LEFT JOIN
student_category sc ON s.student_id = sc.student_id