Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a record when the sum reached a certain threshold

Tags:

sql

I am using SQL and I have a table with three colums: account, transaction_date, Points. Each account will have multiple transaction_dates and Points earned for each transaction.

How do I return the transaction_date when each account reached a certain threshold (i.e. accumulatee 100 Points). Say the first account has 2000 transactions and the first five have each 21 Points. I would like the query to return transaction # 5 because that is when the account reached 100.

Can anybody help? Thanks! Cat


2 Answers

select min(a.transaction_date), a.account from

(select sum(t1.points) as thesum, t2.transaction_date, t2.account 
from table t1
inner join table t2 on t1.account = t2.account and t1.transaction_date <= t2.transaction_date
group by t2.transaction_date, t2.account
having thesum >= 100) a 

group by a.account
like image 103
ʞɔıu Avatar answered Dec 05 '25 11:12

ʞɔıu


Use a triangular join:

In T-SQL:

SELECT account, MIN(dt), MIN(points) 
FROM 
(
    SELECT t1.account, t1.date, sum(t2.points) AS points
    FROM table t1
      INNER JOIN table t2 ON t1.account = t2.account AND t1.dt >= t2.dt
    GROUP BY t1.account, t1.date
    HAVING SUM(t2.points) > 100
) iq
GROUP BY account
like image 24
mwigdahl Avatar answered Dec 05 '25 11:12

mwigdahl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!