And the output that I am looking for is against every hhid, I want to calculate the average of the last 3 months of ttlasset and ttlimcome and the date(frdate) should be the max date.
So for every hhid, on max date,I want to calculate the average of last 3 months of ttlasset and ttlincome if the current month is not complete.
SO output should be like this:
This is the code that I used:
SELECT hhid, MAX(frdate), AVG(ttlincome),AVG(ttlasset)
FROM hhmonthlyprogress WHERE MONTH(frdate) = (SELECT MONTH(NOW())-1) OR MONTH(frdate) = (SELECT MONTH(NOW())-2) OR MONTH(frdate) = (SELECT MONTH(NOW())-3)
FROM hhmonthlyprogress
2
Answers
Hello Please check my SQL Code: I used CTE to solve it:
And The result It produces:
step 1 : finding max date for each hhid
step 2 : using the query from step 1 as derived table and join with the
hhmonthlyprogress
table.step 3: adding WHERE condition
Explanation for
WHERE
conditionThe second condition is basically the same but since there’s no
FIRST_DAY()
function in MySQL that I know of, then I useLAST_DAY()
fromMaxdate
value with 4 month previous interval then addINTERVAL 1 DAY
to get the first day of next month after that.step 4: Finalize query with
AVG()
:Note: I’ve changed
AVG()
toSUM()
then divide by 3 – as a representation of 3 months.Here is updated demo fiddle