一、思路:要求出勤率需要算每门课程 1、签到人数,2、累计在线时长≥10min的人数(一个人可能多次进出直播,需分组累计)。 二、步骤 ①求课程签到人数:将behavior_tb表和course_tb连接,筛选出签到的人相关信息,形成表tb1; ②求累计在线时长≥10min的人数:将attend_tb和course_tb连接,筛出直播开始后在线的人,根据课程分组后计算累计在线时长,形成表tb2; ③将tb1与tb2左连接(因tb1的签到u_id可能多于tb2,用左连接保留),根据课程分组后再计算即可。 select tb1.course_id, tb1.course_name, round(count(if(len>=10, tb2.user_id, null))/count(tb1.user_id)*100,2) as `attend_rate(%)` from (select course_id, course_name, user_id from behavior_tb left join course_tb using(course_id) where if_sign=1) as tb1 left join (select course_id, user_id, sum(timestampdiff(minute, in_datetime, out_datetime)) len from attend_tb left join course_tb using(course_id) where out_datetime>=course_datetime group by course_id, user_id) as tb2 on tb1.user_id=tb2.user_id and tb1.course_id=tb2.course_id group by tb1.course_id, tb1.course_name order by course_id