【问题标题】:How to combine these two queries from different tables into one to calculate percentage?如何将这两个来自不同表的查询合并为一个来计算百分比?
【发布时间】:2020-02-19 16:53:13
【问题描述】:

我有以下查询,该期间有学生出勤:

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

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

【问题讨论】:

    标签: sql postgresql querying


    【解决方案1】:

    可能最简单的方法是使用 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 的类型,您可能必须将其强制转换为数字、实数或浮点数以避免整数数学运算。

    【讨论】:

      【解决方案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;
      

      【讨论】:

        猜你喜欢
        • 2020-10-12
        • 2013-11-22
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 2015-03-15
        • 1970-01-01
        • 2020-01-10
        • 1970-01-01
        相关资源
        最近更新 更多