sql >> Database teknologi >  >> RDS >> PostgreSQL

SQL vælger gennemsnitsscore over datointerval

Noget som dette under forudsætning af created_at er af typen date

select p.name,
       hc.note as current_note,
       av.avg_note
from patients p
   join health_conditions hc on hc.patient_id = p.id
   join (
      select patient_id, 
             avg(note) as avg_note
      from health_conditions hc2
      where created_at between current_date - 30 and current_date - 1
      group by patient_id
    ) avg on t.patient_id = hc.patient_id
where hc.created_at = current_date;

Dette er PostgreSQL-syntaks. Jeg er ikke sikker på, om MySQL understøtter dato-aritmetik på samme måde.

Rediger:

Dette skulle give dig den seneste note for hver patient plus gennemsnittet for de sidste 30 dage:

select p.name,
       hc.created_at as last_note_date
       hc.note as current_note,
       t.avg_note
from patients p
   join health_conditions hc 
     on hc.patient_id = p.id
    and hc.created_at = (select max(created_at) 
                         from health_conditions hc2 
                         where hc2.patient_id = hc.patient_id)
   join (
      select patient_id, 
             avg(note) as avg_note
      from health_conditions hc3
      where created_at between current_date - 30 and current_date - 1
      group by patient_id
    ) t on t.patient_id = hc.patient_id


  1. Throwback i datoer uden weekender

  2. ora:12505:TNS:lytteren kender i øjeblikket ikke til SID givet i forbindelsesbeskrivelsen (DBD-FEJL:OCIServerAttach)

  3. hvorfor forespørgslen tager for lang tid

  4. mysql ...i hvor klausulen er tvetydig