SQL Добавление флага на основе одного столбца с несколькими значениями - PullRequest
0 голосов
/ 07 сентября 2018

Я пытаюсь добавить флаг в таблицу на основе одного столбца, который включает несколько значений. Например ..

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

Ответы [ 3 ]

0 голосов
/ 07 сентября 2018

Вы можете попробовать с 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
0 голосов
/ 07 сентября 2018

Другой вариант - использовать 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;
0 голосов
/ 07 сентября 2018

Вы можете использовать условное агрегирование и выражение 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;
...