Skip to content

Instantly share code, notes, and snippets.

@mshakhomirov
Created November 24, 2022 15:24
Show Gist options
  • Save mshakhomirov/ea4de9144b97bf8c196cab07609c309e to your computer and use it in GitHub Desktop.
Save mshakhomirov/ea4de9144b97bf8c196cab07609c309e to your computer and use it in GitHub Desktop.
with top_spenders as (
select 1 as user_id, 100 as total_spend, 11 as reputation_level union all
select 2 as user_id, 150 as total_spend, 11 as reputation_level union all
select 3 as user_id, 250 as total_spend, 11 as reputation_level union all
select 11 as user_id, 1000 as total_spend, 22 as reputation_level union all
select 22 as user_id, 1500 as total_spend, 22 as reputation_level union all
select 33 as user_id, 2500 as total_spend, 22 as reputation_level
)
, data as (
select
user_id
,total_spend
,reputation_level
,first_value(total_spend)
over (partition by reputation_level order by total_spend desc
rows between unbounded preceding and unbounded following) as top_spend
from top_spenders
)
select
user_id
,reputation_level
,total_spend
,top_spend as top_spend_by_rep_level
,total_spend - top_spend as delta_in_usd
from data
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment