让我们看看我拥有的示例简化表:
Classes table:
class_id
1
2
3
Students table:
id, class_id, name, sex
1, 1, John, M
2, 1, Mike, M
3, 3, Rob, M
4, 2, Kate, F
5, 2, Sophie, F
6, 2, Laura, F
7, 3, Julia, F
我想在栏上注明男,女或混合班级
我尝试过这种方法,但是它不起作用,就像只检查班级中的第一个学生,然后将其值分配给结果。类别“ 3”应“混合”
select class_id,
case when s.sex = 'M' then 'Male'
when s.sex = 'F' then 'Female'
when s.sex = 'F' and s.sex = 'M' then 'Mixed'
end as class_type
from class c
join students as s on s.class_id = c.class_id
答案 0 :(得分:0)
您可以进行聚合:
SELECT C.class_id,
(CASE WHEN MIN(S.SEX) <> MAX(S.SEX) THEN 'MIXED' ELSE CAST(MIN(S.SEX) AS text) END) AS class_type
FROM Classes C INNER JOIN
Students S
ON S.class_id = C.class_id
GROUP BY C.class_id;
但是,如果只需要JOIN
而不是Classes
表中的更多信息,那么class_id
和Classes
就是多余的。