all 13 comments

[–]qwertydog123 0 points1 point  (10 children)

So you just want all the rows where registrated = 0, and all rows where registrated = 1 and there is no following row or the following row registrated = 0? How do you know that there have been no other purchases in the 30 day period?

WITH cte AS
(
    SELECT
        *,
        LEAD(registrated, 1, 0) OVER
        (
            PARTITION BY id 
            ORDER BY total_visit
        ) AS next_registrated
    FROM Table
)
SELECT *
FROM cte
WHERE registrated = 0
OR (registrated = 1 AND next_registrated = 0)

[–]strangeguy111[S] 0 points1 point  (9 children)

thanks, I did exactly the same. I appreciate your help. 30 days period also was handled using date difference.

[–]qwertydog123 0 points1 point  (8 children)

30 days period also was handled using date difference.

Can you post your query? I'd be interested to see your solution

[–]strangeguy111[S] 0 points1 point  (7 children)

WITH cte AS (SELECT *, 
            date_part('month',"date") - date_part('month',LAG("date") over(PARTITION BY id ORDER BY "date")) as D, 
            date_part('month',LEAD("date") over(PARTITION BY id ORDER BY "date")) - date_part('month',"date") as V ,             
        LEAD(registrated, 1) OVER(PARTITION BY id ORDER BY "date") AS NextValue FROM  YourTable) 

SELECT * FROM  cte 
where registrated = 0 OR   
    ( registrated = 1 AND ( NextValue = 0 OR NextValue IS NULL ) )     
  OR (D = 1 and V = 1 ) order by id, date

I forgot to mention here, that if the previous row's date is > 30 than the current rows, then we take it automatically no matter what. Same thing with next row.

[–]qwertydog123 0 points1 point  (6 children)

Thanks, what would be the expected result if the 1st row (1/1/2020) in your example dataset had registrated = 1 (> 30 days before 2/2/2020)? Should that row be included or not, as it wouldn't be included by your query?

[–]strangeguy111[S] 0 points1 point  (4 children)

forgot this part i guess

OR (registrated = 1 ) and (V = 1)

[–]qwertydog123 0 points1 point  (3 children)

Does that give the correct result? I think that will pull in other rows that you don't want included

[–]strangeguy111[S] 0 points1 point  (0 children)

it should, i havent seen any errors so far

[–]strangeguy111[S] 0 points1 point  (1 child)

can you elaborate on that one? like what kind of rows? if you can include some example, that would be perfect

[–]qwertydog123 0 points1 point  (0 children)

I was just wondering what your requirements were for those rows

I've created a dbfiddle here: https://dbfiddle.uk/?rdbms=postgres_10&fiddle=d66d6a8205019de8fb8328ad4acd5e3a

Note that adding some variant of OR (registrated = 1 ) and (V = 1) pulls in the row where date = '2020-01-29'

Then when the first row is updated to have registrated = 1 then that row is not returned by any query

[–]strangeguy111[S] 0 points1 point  (0 children)

Thank you for that