1

The slope of line on X-axis is days and Y-axis is balance.

I need to find the steepest slope.

I am thinking to try

SELECT (MAX(balance)-MIN(balance)) / DATEDIFF(MAX(date),MIN(date)) AS time
FROM account
GROUP BY account_id

Does this work? Anyone having simple ways to solve it? Thanks in advance :)

0

1 Answer 1

0

I don't think your answer will work.

It will get the max date, max balance, and min date, and min balance for a given account. Your max date will be the most recent date, but max balance may be from months ago. So your growth over time gets messed up. Your balance may be $1 on day 1, $1M on day 2, and $2 on day 1000. Your math will show $1M - $1 over 1000 days. I think you want it to show $2 - $1 over 1000 days.

I prefer the following. You may have to check it for syntax but the logic is there. Basically you partition over rows to order all the balances for a given account in order of the date of the balance. The most recent balance for each account is ranked 1. Your WHERE clause then makes your table only contain the most recent balances for each account. You then join that to a table that does the same thing, except its all the old balances. So now you have the oldest and newest balance for each account.

Then you can select to get the newest less the oldest balance, and divide that by the number of days between those balance. The top is the growth, the denominator is the time. The largest factorial that pops out will be your answer - the growth over time.

SELECT 
    mostRecentBalances.balance as mostRecentbalance,
    mostRecentBalances.date as recentDate,
    oldestBalances.balance as oldestBalance,
    oldestBalances.date as OldestDate,
    (mostRecentBalances.balance - oldestBalances.balance) / DATEDIFF(MAX(mostRecentBalances.date),MIN(oldestBalances.date)) as growthFactor
FROM
    (SELECT 
        balance,
        (ROW_NUMBER() over (PARTITION BY balance GROUP BY account_id ORDER BY date DESC) as RowNumber 
    WHERE
        RowNumber = 1 ) mostRecentBalances
INNER JOIN
    (SELECT 
        balance,
        (ROW_NUMBER() over (PARTITION BY balance GROUP BY account_id ORDER BY date ASC) as RowNumber 
    WHERE
        RowNumber = 1 ) OldestBalances
on mostRecentBalances.account_id = oldestBalances.account_id
ORDER BY
    growthFactor DESC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.