X
X
XenK2018-09-28 18:30:10
PostgreSQL
XenK, 2018-09-28 18:30:10

Select minimum date, plus N days?

There is such a table, with bonuses for the user:

╔═════════╦════════╦════════════════════════╗
║ user_id ║ amount ║ created_at             ║
╠═════════╬════════╬════════════════════════╣
║ 1       ║ 50     ║ 2018-09-02 16:59:58.10 ║
╠═════════╬════════╬════════════════════════╣
║ 1       ║ 120    ║ 2018-09-09 12:59:58.10 ║
╠═════════╬════════╬════════════════════════╣
║ 3       ║ 25     ║ 2018-07-05 16:59:58.10 ║
╠═════════╬════════╬════════════════════════╣
║ 3       ║ 90     ║ 2018-07-07 16:59:58.10 ║
╚═════════╩════════╩════════════════════════╝


You need to get the amount for each user, from the moment of the first receipt of the bonus + 5 days . How to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nozzy, 2018-09-28
@nozzy

select
t1.user_id,
sum(t1.amount),
count(*) as count
from your_table t1
inner join (
    select
    t2.user_id,
    t2.created_at
    from your_table t2
    where not exists (
        select 1 
        from your_table
        where user_id = t2.user_id
        and created_at < t2.created_at
    )
)   t3 on t3.user_id = t1.user_id 
    and t1.created_at between t3.created_at and t3.created_at + interval 5 day
group by t1.user_id
having(count <= 5)

D
Dmitry Telepnev, 2018-09-29
@TelepnevDmitriy

select
    table1.user_id, count(table1.amount)
from table1
join (
    select
        user_id, min(created_at) minimal_date
    from table1
    group by user_id
)dates on dates.user_id = table1.user_id
    and table1.created_at between dates.minimal_date and (dates.minimal_date + interval '5d')
group by table1.user_id

K
kylemaclohlan, 2018-10-01
@kylemaclohlan

WITH table1 ( user_id, amount, created_at)
AS (VALUES
      (1, 50,  '2018-09-02 16:59:58.10' :: TIMESTAMP)
    , (1, 120, '2018-09-09 12:59:58.10' :: TIMESTAMP)
    , (3, 25,  '2018-07-05 16:59:58.10' :: TIMESTAMP)
    , (3, 90,  '2018-07-07 16:59:58.10' :: TIMESTAMP)
)
SELECT t1.user_id,sum(t1.amount)
FROM table1 t1
JOIN LATERAL (SELECT min(t2.created_at) AS mi
              FROM table1 t2
              WHERE t2.user_id = t1.user_id
     ) t3 ON TRUE
WHERE t1.created_at - t3.mi <= '5 day'
GROUP BY t1.user_id
;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question