我有以下查询,显示该期间的学生出勤率:
select total_presences from diary.period_attendance
where id_customer = 1492 and id_diary_period = 172818 and id_user = 835603;
我有同期的课数。
select count(*) from diary.lesson where id_diary_period = $1 and id_customer = $2 and end_date < now();
我想将total_presences除以课程计数,以获得学生的出勤率。
如何在单个查询中做到这一点?
答案 0 :(得分:2)
您可以使用交叉联接或联合
SELECT total_presences from diary.period_attendance
where id_customer = 1492 and id_diary_period = 172818 and id_user = 835603 t1;
CROSS APPLY
(SELECT t1.total_presences /count(*)
from diary.lesson
where id_diary_period = $1 and id_customer = $2 and end_date < now();
) t2;
答案 1 :(得分:2)
可能最简单的方法是使用CTE:
WITH lesson_count AS (
select count(*) as lessons
from diary.lesson
where id_diary_period = $1 and id_customer = $2 and end_date < now()
)
select total_presences, total_presences/lessons
from diary.period_attendance, lesson_count
where id_customer = 1492
and id_diary_period = 172818
and id_user = 835603;
根据total_presences的类型,可能必须将其强制转换为数字,实数或浮点数,以避免整数数学。