Skip to content
Advertisement

How to calculate total balance in sql using sum?

updated question —

I have a table that contains the following columns:

I need to calculate the balance based on the update date. In some cases there can be the same update_date for two different records. When I have this, I want to grab the lower value of the balance.

This is the query I have so far:

In the query above, it’s is grabbing the 75, rather than the 0 after I try to only grab the LAST balance.

Is there a way to include in the qualify query to grab the last balance but if the dates are the same, to grab the lowest balance?

Advertisement

Answer

why is the second query, showing 4 different record balances?

That is the point of “running total”. If the goal is to have a single value per entire window then order by should be skipped:

The partition by clause could be futher expanded with date to produce output per user_key/date:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement