sample_input_table
user name action date
1 aaa view 2020-09-03
2 bbb view 2020-09-02
3 ccc view 2020-08-28
4 ddd view 2020-08-25
1 aaa purchase 2020-09-09
I have a table with huge number of rows, the table looks like above.
question
purchase
action andpurchase
must have row with view
actionview
action will be in the date range of purchase_date(2020-09-09
) and purchase_date - 7days(2020-09-02
).I want to achieve these 3 point in one sql query
sample_output
user name action date
1 aaa purchase 2020-09-09
if we see sample output from the sample input
view
actionview
was there in the timeframe of 2020-09-09
and 2020-09-02
(purchased_date, purchased_date - 7 days)Can anyone suggest some solution for this?
You can use exists
:
select t.*
from mytable t
where t.action = 'purchase' and exists (
select 1
from mytable t1
where
t1.user = t.user
and t1.action = 'view'
and t1.date >= t.date - interval '7' day
and t1.date < t.date
)