sql >> Databasteknik >  >> RDS >> Oracle

Samla flera poster efter datum

Jag antar att (patient_id, adherence_date, scheduled_time) är unik i ditt bord, vilket innebär att en patient kan boka en gång per "slot" och 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;

Logiken fungerar så här:

  • om acknowledged_at är null så aggregerar vi 0 (via nvl2)
  • om acknowledged_at är inte null då aggregerar vi 1 (via nvl2)
  • om det inte finns någon post för denna tidslucka samlar vi ihop null (eftersom ... misslyckades)


  1. Mysql-tabell med sammansatt index men inte primärnyckel

  2. db2 motsvarighet till MySql REPLACE INTO

  3. SQL Server Performance TOP CPU Query -2

  4. Den parameteriserade frågan förväntar sig parametern som inte angavs