How do you calculate a running total, such as a running salary, where the first entry is 1000 rupees and the second is 3000 rupees, accumulating over time?
💡 Model Answer
To compute a running total you can use a window function that sums the values up to the current row. In SQL this is typically written as:
SELECT
employee_id,
salary,
SUM(salary) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS running_salary
FROM
employee_payments;
The ORDER BY clause defines the sequence in which rows are processed, and ROWS UNBOUNDED PRECEDING tells the engine to include all rows from the start of the partition up to the current row. If you are working in a language like Python with pandas you can achieve the same with the cumsum() method:
df['running_salary'] = df['salary'].cumsum()
Both approaches give you a cumulative sum that updates as you iterate through the dataset. Complexity is O(n) for the entire table, and the operation is typically very fast because it is implemented in the database engine or vectorized in pandas.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500