購入履歴テーブル
人物ID 購入日 購入金額
------ -------- --------
1 2007/1/1 300
1 2007/1/2 400
1 2007/1/4 400
1 2007/1/5 600
1 2007/1/6 600
2 2007/1/1 600
2 2007/1/2 300
3 2007/1/2 2500
4 2007/1/2 1500
4 2007/1/6 1500
5 2007/1/6 1500
5 2007/1/8 1500
6 2007/1/1 500
6 2007/1/8 1000
6 2007/1/9 1200
任意の三日間で、
購入金額の合計が2000を越えた人物IDの
全レコードを出力する
出力結果
人物ID 購入日 購入金額
------ -------- --------
3 2007/1/2 2500
5 2007/1/6 1500
5 2007/1/8 1500
6 2007/1/1 500
6 2007/1/8 1000
6 2007/1/9 1200
create table 購入履歴 as
select 1 as 人物ID,to_date('2007/1/1','fmyyyy/mm/dd') as 購入日,300 as 購入金額 from dual
union select 1,to_date('2007/1/2','fmyyyy/mm/dd'), 400 from dual
union select 1,to_date('2007/1/4','fmyyyy/mm/dd'), 400 from dual
union select 1,to_date('2007/1/5','fmyyyy/mm/dd'), 600 from dual
union select 1,to_date('2007/1/6','fmyyyy/mm/dd'), 600 from dual
union select 2,to_date('2007/1/1','fmyyyy/mm/dd'), 600 from dual
union select 2,to_date('2007/1/2','fmyyyy/mm/dd'), 300 from dual
union select 3,to_date('2007/1/2','fmyyyy/mm/dd'),2500 from dual
union select 4,to_date('2007/1/2','fmyyyy/mm/dd'),1500 from dual
union select 4,to_date('2007/1/6','fmyyyy/mm/dd'),1500 from dual
union select 5,to_date('2007/1/6','fmyyyy/mm/dd'),1500 from dual
union select 5,to_date('2007/1/8','fmyyyy/mm/dd'),1500 from dual
union select 6,to_date('2007/1/1','fmyyyy/mm/dd'), 500 from dual
union select 6,to_date('2007/1/8','fmyyyy/mm/dd'),1000 from dual
union select 6,to_date('2007/1/9','fmyyyy/mm/dd'),1200 from dual;
select 人物ID,to_char(購入日,'fmyyyy/mm/dd') as 購入日,購入金額
from 購入履歴 a
where 人物ID in(select b.人物ID
from 購入履歴 b
where (select sum(c.購入金額)
from 購入履歴 c
where c.購入日 between b.購入日-3+1 and b.購入日
and c.人物ID = b.人物ID) > 2000)
order by 人物ID,a.購入日;
in述語の引数のサブクエリで、 任意の三日間で、 購入金額の合計が2000を越えた人物IDの集合を求めてます