0

I'd like to calculate an average amount of money spent per day for the past 7, 30, 90 and 180 days. I know how to do it using PL/pgSQL, but I'd prefer to do it in one query if possible. Something like this:

SELECT SUM(amount)/days
FROM transactions
WHERE created_at > CURRENT_DATE - ((days || ' day')::INTERVAL)
AND days = ANY(ARRAY[7,30,90,180]);

ERROR: column "days" does not exist

1 Answer 1

1

You can use unnest to convert the array into a table and the use a correlated subquery to calculate the average:

SELECT
    days,
    (SELECT SUM(amount)/days
     FROM transactions
     WHERE created_at > CURRENT_DATE - ((days || ' day')::INTERVAL)
    ) AS average
FROM unnest(ARRAY[7,30,90,180]) t(days)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.