SQL根据具有多个值的一列添加标志
我试图在基于表的一列中添加一个包含多个值的标志。例如SQL根据具有多个值的一列添加标志,sql,amazon-redshift,Sql,Amazon Redshift,我试图在基于表的一列中添加一个包含多个值的标志。例如 Student_id | Exam_type 123 Practice 123 Recertification 123 Certification 456 Practice 456 Certification 789 Recertification
Student_id | Exam_type
123 Practice
123 Recertification
123 Certification
456 Practice
456 Certification
789 Recertification
135 Practice
246 Practice
246 Certification
我希望能够标记哪些学生参加了实践考试。
输出需要是:
Student_id | Practice_taken
123 Y
456 Y
789 N
135 Y
246 Y
您可以使用条件聚合和
大小写表达式:
select student_id,
(case when sum(exam_type = 'Practice' then 1 else 0 end) > 0
then 'Y' else 'N'
end) as practice_taken
from t
group by student_id;
您可以尝试使用row_number()
其他选项是使用exists
:
select student_id, (case when exists (select 1
from table t1
where t1.student_id = t.student_id and
t1.Exam_type = 'Practice'
)
then 'Y' else 'N'
end) as practice_taken
from table t
group by student_id;
select student_id, (case when exists (select 1
from table t1
where t1.student_id = t.student_id and
t1.Exam_type = 'Practice'
)
then 'Y' else 'N'
end) as practice_taken
from table t
group by student_id;