Home > database > How SQL check day average final balance
How SQL check day average final balance
Time:10-28
Account every day, take out, the balance has been change, cycle for 24 hours, take every last one balance, to calculate the month or year, on average, how to do? Cusid date time balance 001 20190801 10:05:00 10000 001 20190801 10:06:01 5000 001 20190801 15:15:00 250000 001 20190801 23:05:00 5000 001 20190802 09:10:00 100000 001 20190802 10:06:01 5000 001 20190802 15:15:00 250000 001 20190802 15:20:00 0 001 20190803 08:32:00 50000 .
CodePudding user response:
The test data
-If not object_id (N 'Tempdb for.. # T ') is null Drop table # T Go Create table # T ([cusid] nvarchar (23), date [date], [time] time, [this] int) Insert # T Select N '001', '20190801', '10:05:00, 10000 union all Select N '001', '20190801', '10:06:01, 5000 union all Select N '001', '20190801', '15:15:00, 250000 union all Select N '001', '20190801', '23:05:00, 5000 union all Select N '001', '20190802', '09:10:00, 100000 union all Select N '001', '20190802', '10:06:01, 5000 union all Select N '001', '20190802', '15:15:00, 250000 union all Select N '001', '20190802', '15:20:00' 0 union all Select N '001', '20190803', '08:32:00' 50000 Go - the end of the test data ; WITH cte AS ( Select *, ROW_NUMBER () OVER (PARTITION BY the date the ORDER BY the time DESC) rn from # T ) SELECT the MONTH (cte) date) AS the date, AVG (cte) balance) AS the balance FROM cte WHERE rn=1 GROUP BY the MONTH (cte) date)
CodePudding user response:
I can not describe clearly, I want every day finally a balance, the average of the data, should be 8/1 three days finally a 5000 + 8/2 finally a 0 + 50000=55000/8/3 balance 3 on average