如何结合 2 cte 进行分组

how to combine 2 cte to get grouping

嗨,我需要帮助结合 2 个 cte 来确定出勤率达到 100 但考试不及格的人

这是我的第一个 cte

with main as(
select ca.STUDENT_ID,
    ca.SCHEDULE_ID,
    s.COURSE_ID,
    co.NAME as course_name,
    st.NAME,
    count(ca.ID) as total_attendance,
    ((CHAR_LENGTH(s.COURSE_DAYS) - CHAR_LENGTH(REPLACE(s.COURSE_DAYS , ',', '')) + 1) * 13) as attendance_needed
from univ.course_attendance ca 
    left join univ.schedule s on ca.SCHEDULE_ID = s.ID
     left join univ.student st on ca.SCHEDULE_ID = st.ID 
     left join univ.course co  on ca.SCHEDULE_ID  = co.ID 
group by ca.STUDENT_ID, ca.SCHEDULE_ID
)
select *,total_attendance/attendance_needed as attendance_percentage
from main
order by 1,2;

第二次cte

;with inputdata as 
(
 select es.STUDENT_ID,es.EXAM_ID,es.SCORE,e.PASS_THRESHOLD, s.NAME , c.NAME as Course_name, es.EXAM_DT, 
    case 
     when SCORE>=PASS_THRESHOLD then 'PASS'
     else 'Fail'
    end as Flag
    from exam_submission es 
    left join student s  on es.STUDENT_ID  = s.ID
    left join exam e    on es.EXAM_ID  = e.ID 
    left join course c  on e.COURSE_ID  = c.ID  
)    
 select * from inputdata I
join 
 ( select student_id,exam_id from 
    inputdata 
    group by student_id, exam_id    
)T on I.student_id=T.student_id and I.exam_id=T.exam_id
order by exam_dt asc

结果:

我需要什么学生姓名、课程名称、出勤率和标志“failed/pass”

只需在单个 CTE 中链接多个 table 表达式,方法是引入“别名”,例如第一个 CTE 的 main_ordered 和第二个 CTE 的 inputdata_grouped。我坚持原来的命名,但它可以改进。

with 
main as (
   select ca.STUDENT_ID,
      ...
   group by ca.STUDENT_ID, ca.SCHEDULE_ID),
main_ordered as (
   select *,total_attendance/attendance_needed as attendance_percentage
      ...
   order by 1,2),
inputdata as (
   select es.STUDENT_ID,es.EXAM_ID,es.S...
      ...),
inputdata_grouped as (
   select * from inputdata I
   ...
   group by student_id, exam_id...
   ...
   order by exam_dt asc)
select *
from main_ordered join inputdata_grouped on ...