代码之家  ›  专栏  ›  技术社区  ›  jatsen

如何根据ID合并两个表,然后从第二个表中获取日期值

  •  0
  • jatsen  · 技术社区  · 6 年前

    我有两张桌子

    Table 1 - student_id number, class_type varchar2(10), class_time date, attn_time date.
    
    Table 2 - student_id number, attendance varchar2(5), attn_recorded_time date.
    

    我在这里生成一个报告,我需要打印表1中的所有值,并根据某些条件打印表2中记录的附加信息或匹配值“时间”。

      SELECT a.student_id ,
      a.class_type,
      a.class_time,
      b.attn_recorded_time
    FROM student_details a
    LEFT JOIN attendance_details b
    ON a.student_id    = b.student_id
    WHERE a.class_time > b.attn_recorded_time
    AND b.attn_recorded_time BETWEEN a.class_time AND (a.class_time - 1/24)
    ORDER BY a.student_id,
      a.class_time;
    

    所以这里的条件是上课时间应该总是大于出勤时间,并且在上课时间和上课时间之间-1小时。

    我正在尝试使用merge语句实现相同的目标

    merge INTO student_details a USING attendance_details b ON (a.student_id = b.student_id)
    WHEN matched THEN 
    update set a.attn_time = b.attn_recorded_time
    where b.attn_recorded_time between a.class_time and a.class_time- 1/24;
    

    表1的数据

    Student_id   class_type  class_time            attn_time
       1203       English    2018-09-10 11:00:00   
       1203       Maths      2018-09-10 11:30:00   
    

    表2的数据

    Student_id    attendance    attendance_recorded_time
    1203             Y          2018-09-10 10:00:00
    1203             Y          2018-09-10 11:00:00
    1203             Y          2018-09-10 08:00:00
    1203             Y          2018-09-10 09:00:00
    

    所需数据

    Student_id     class_type  class_time             attn_time         
    1203             English   2018-09-10 11:00:00    2018-09-10 10:00:00
    1203             Maths     2018-09-10 11:30:00    2018-09-10 11:00:00
    

    尽管同一个学生有多个可用的数据,但我需要根据上课时间检索最新的出勤记录时间。

    如何实现上述输出,我在这里做错了什么?

    谢谢你抽出时间。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ponder Stibbons    6 年前

    在你 where 先放低值(in between )或者像这样做:

    demo

    select * 
        from student_details a
        join attendance_details b using (student_id)
        where class_time - interval '1' hour <= attn_recorded_time 
          and attn_recorded_time < class_time
    
        2
  •  0
  •   jatsen    6 年前

    请尝试如下操作以获得所需的输出。

    SELECT t.your_column
    FROM
      (SELECT DISTINCT a.Student_id,
        MAX(b.attendance_recorded_time),
        a.class_type,
        MAX(a.class_time)
      FROM student_details
      LEFT JOIN b
      ON a.student_id    = b.student_id
      WHERE a.class_time > b.attn_recorded_time
      AND b.attn_recorded_time BETWEEN a.class_time AND (a.class_time - 1/24)
      GROUP BY attendance_recorded_time,
        class_time
      ORDER BY a.student_id,
        a.class_time
      ) ;