sql >> Databáze >  >> RDS >> Oracle

Agregace více záznamů podle data

Předpokládám, že (patient_id, adherence_date, scheduled_time) je jedinečný ve vaší tabulce, což znamená, že pacient se může rezervovat jednou na "slot" a datum.

with medication_adherences  as(
-- This is your test data
   select 10049 as patient_id, 1 as id, date '2017-10-01' as adherence_date, 'morning'    as scheduled_time, timestamp '2017-10-31 19:59:19' as acknowledged_at from dual union all
   select 10049 as patient_id, 2 as id, date '2017-10-01' as adherence_date, 'afternoon'  as scheduled_time, null                            as acknowledged_at from dual union all                          
   select 10049 as patient_id, 3 as id, date '2017-10-01' as adherence_date, 'night'      as scheduled_time, timestamp '2017-10-31 19:59:19' as acknowledged_at from dual union all
   select 10049 as patient_id, 4 as id, date '2017-10-02' as adherence_date, 'morning'    as scheduled_time, timestamp '2017-10-31 19:59:19' as acknowledged_at from dual union all
   select 10049 as patient_id, 5 as id, date '2017-10-02' as adherence_date, 'afternoon'  as scheduled_time, timestamp '2017-10-31 19:59:19' as acknowledged_at from dual union all
   select 10049 as patient_id, 6 as id, date '2017-10-02' as adherence_date, 'evening'    as scheduled_time, timestamp '2017-10-31 19:59:19' as acknowledged_at from dual union all
   select 10049 as patient_id, 7 as id, date '2017-10-02' as adherence_date, 'night'      as scheduled_time, null                            as acknowledged_at from dual
)
select adherence_date
      ,sum(case when scheduled_time = 'morning'   then nvl2(acknowledged_at,1,0) end) as morning
      ,sum(case when scheduled_time = 'afternoon' then nvl2(acknowledged_at,1,0) end) as afternoon
      ,sum(case when scheduled_time = 'evening'   then nvl2(acknowledged_at,1,0) end) as evening
      ,sum(case when scheduled_time = 'night'     then nvl2(acknowledged_at,1,0) end) as night
  from medication_adherences 
 where patient_id = 10049
 group
    by adherence_date;

Logika funguje takto:

  • pokud má canceld_at hodnotu null, agregujeme 0 (přes nvl2)
  • jestliže canceld_at není null pak agregujeme 1 (přes nvl2)
  • pokud pro tento časový úsek neexistuje žádný záznam, agregujeme hodnotu null (protože případ, kdy ... se nezdařilo)


  1. Události na straně serveru s PHP a MySQL

  2. Poskytování oprávnění systému postgres ke kopírování (Windows 8)

  3. Vyhledejte konkrétní řetězec ve sloupci Oracle clob

  4. Osvědčený postup:Uložte hodnoty velkých formulářů do databáze