Oracle
 sql >> база данни >  >> RDS >> Oracle

Обединяване на множество записи по дата

Предполагам, че (patient_id, adherence_date, scheduled_time) е уникален във вашата таблица, което означава, че пациент може да резервира веднъж за "слот" и дата.

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;

Логиката работи по следния начин:

  • ако acknowledged_at е null, тогава събираме 0 (чрез nvl2)
  • ако acknowledged_at е не null, тогава събираме 1 (чрез nvl2)
  • ако няма запис за този времеви интервал, ние обобщаваме нула (от случай, когато ... е неуспешен)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Мистериозен SQL блокира изпълнението на съхранената ми процедура в ORACLE

  2. Не мога да вляза в базата данни като SYS с Oracle SQL Developer

  3. ROWDEPENDENCIES Горни разходи в Oracle

  4. ALTER &DROP Table DDL с непосредствено изпълнение в базата данни на Oracle

  5. Пространството от имена на System.Data.OracleClient е прекратено?