I have the following table (called report) in SQL Server:
+---------+------------------------+---------+
| User_id | timestamp | balance |
+---------+------------------------+---------+
| 1 |2021-04-29 09:31:10.100 | 10 |
| 1 |2021-04-29 09:35:25.800 | 15 |
| 1 |2021-04-29 09:36:30.550 | 5 |
| 2 |2021-04-29 09:38:15.009 | 100 |
+---------+------------------------+---------+
I would like to group the opening balance, closing balance and net movement of all users between a date period (only if the user has a record within that date range)
I would like the following output if my query asked for everything between 2021-04-29 and 2021-04-30
+---------+-----------------+-----------------+--------------+
| User_id | opening_balance | closing_balance | net_movement |
+---------+-----------------+-----------------+--------------+
| 1 | 10 | 5 | -5 |
| 2 | 100 | 100 | 0 |
+---------+-----------------+-----------------+--------------+
I am unclear on what best approach to take, should I be making multiple queries for the TOP 1 of the balance ([TOP 1 order by timestamp] AND [TOP 1 order by timestamp DESC]) and I am unclear on how to calculate the net movement if I do manage to get the values.
Any clues or nudges in the right direction would be most appreciated.