SQL Query / Stored proc to count monthly average of daily sums
-
16-06-2021 - |
Domanda
I'm using Firebird 2.1.
I could use some help creating the following query or stored procedure.
I need to list the monthly averages of daily sums of petty cash transactions.
Let me explain:
TABLE PettyCash(RowID, TDate, InOut, Amount)
- 1 2012-01-01 0 5.000
- 2 2012-01-01 1 3.000
- 3 2012-01-05 0 4.000
- 4 2012-01-23 1 2.000
- 5 2012-02-20 1 5.000
InOut = 0 if it's an incoming, InOut = 1 if it's an outgoing transaction
What the query has to do is to calculate the balance for every day in the month, sum up the amounts and then divide it by the number of days in the current month.
If there is no transaction on a given day, the balance stays the same.
So in January it goes like this:
- 2012-01-01 2.000
- 2012-01-02 2.000
- 2012-01-03 2.000
- ...
- 2012-01-05 6.000
and so on.
To complicate the matter there is always a starting balance being carried from the last year (that adds up to the balances this year).
I calculate that like this:
SELECT SUM(IIF(INOUT = 0, AMOUNT, -AMOUNT))
FROM PETTYCASH
WHERE TDATE < '2012-01-01';
The resulting query or stored proc should be given a start date and an end date - the start date is always the first day of a year, the end date could be a given day of the year, ie.: StartDate = 2012-01-01, EndDate = 2012-06-23
If the EndDate is not the last day of a month, the average of the last months should be divided only by the last day, in the example June should be divided by 23 instead of 30.
The result should be like this: Month | Average of daily sums for the month
Any help would be greatly appreciated!
Thanks
Soluzione
What you need is a subquery. The inner subquery calculates the sum on each day, the outer query calculates the averages.
I am not familiar with firebird's date functions, but it does have the "extract" function. The following uses this to get what you want:
select yr, mon, avg(amt)
from (SELECT extract(year from tdate) as yr, extract(month from tdate) as mon,
extract(day from tdate) as day,
SUM(IIF(INOUT = 0, AMOUNT, -AMOUNT)) as amt
FROM PETTYCASH
WHERE TDATE < '2012-01-01'
group by extract(year from tdate), extract(month from tdate),
extract(day from tdate)
) t
group by yr, mon
order by yr, mon