我正在尝试在包含多个值的基于一列的表中添加标志。例如。
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
答案 0 :(得分:1)
您可以使用条件聚合和case
表达式:
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;
答案 1 :(得分:0)
您可以尝试使用row_number()
select student_id, case when max(rn)=1 then 'Y' else 'N' end as Practice_taken from
(select student_id,row_number() over(partition by student_id order by case when exam_type = 'Practice' then 1 else 0 end desc) as rn
from t) where rn=1
group by student_id
答案 2 :(得分:0)
其他选择是使用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;