如何将来自不同表的这两个查询合并为一个以计算百分比?

时间:2019-10-23 12:28:55

标签: sql postgresql querying

我有以下查询,显示该期间的学生出勤率:

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除以课程计数,以获得学生的出勤率。

如何在单个查询中做到这一点?

2 个答案:

答案 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的类型,可能必须将其强制转换为数字,实数或浮点数,以避免整数数学。