Skip to content

Instantly share code, notes, and snippets.

@savadev
Forked from ks--ks/sampling_example.sql
Created October 25, 2024 04:14
Show Gist options
  • Select an option

  • Save savadev/c9fcd56ea27375f1d300d0fdc2f6ca75 to your computer and use it in GitHub Desktop.

Select an option

Save savadev/c9fcd56ea27375f1d300d0fdc2f6ca75 to your computer and use it in GitHub Desktop.
Data sampling in PostgreSQL
-- sample data and assign new or returning user type
sampledata as (
select a.user_id,
a.created_at
, case
when a.created_at between a.firstdate and a.firstdate+27 then 'new'
else 'returning'
end as type
from (
select user_id
, left(right(user_id, 4), 2) as sample
, created_at
, firstdate::date as first_date
from data
group by 1, 2, 3, 4
) a
where a.sample='04'
group by 1, 2
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment