sql - find a date when sales for id reach some level -
i need find date, when sum paid every user exceeded $100. have table in below format:
+----------------------------------------+------------+----+ | pay_date, user_id, transaction_sum | | | +----------------------------------------+------------+----+ | 01/01/14, a1, $2 | | | | 01/01/14, a2, $5 | | | | 01/01/14, b1, $10 | | | | 03/01/14, a1, $2 | | | | 03/01/14, b1, $2 | | | | 03/01/14, c1, $5 | | | | 04/01/14, a3, $2 | | | | 04/01/14, a3, $20 | | | | 04/01/14, c1, $5 | | | +----------------------------------------+------------+----+ ... (ordered pay_date) i'd have in result table this:
user_id, pay_date a1, 03/03/14 a2, 30/03/14 a3, 22/05/14 b1, 01/01/15 c1, 12/10/14 the total cumulative amount of money paid users exceed $100, need date when exceeded. other users not exceed, don't need them in table.
apologies if haven't explained enough thanks
afaik redshift supports windowed aggregate functions:
select user_id, min(pay_date) ( select pay_date, user_id, sum(transaction_sum) -- cumulative sum based on pay_date on (partition user_id order pay_date rows unbounded preceding) cum_sum tab ) dt cum_sum > 100 -- rows cumulative sum exceeds limit group user_id
Comments
Post a Comment