sql >> データベース >  >> RDS >> Oracle

複数のレコードを日付別に集計する

    (patient_id, adherence_date, scheduled_time) と仮定しています はテーブル内で一意です。つまり、患者は「スロット」と日付ごとに 1 回予約できます。

    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;
      

    ロジックは次のように機能します:

    • acknowled_at が null の場合、0 を集計します (nvl2 経由)
    • ackled_at が not の場合 null の場合は 1 を集計します (nvl2 経由)
    • このタイムスロットのレコードがない場合は、null を集計します (... が失敗した場合)


    1. T-SQLを使用してリンクサーバーオプションを編集する方法

    2. foreachループを使用して同じIDの複数の行を更新します

    3. MySQLの文字列から不要な先頭文字を削除する方法

    4. Oracle での DateDiff() の使用