0

I would like to find the average of a column for 2 time periods but I'm unsure how to display both in single query. I know the below won't work but I'm looking for the proper syntax:

SELECT
AVG(amount) AS avg_amt
FROM table
WHERE day >= date('2019-05-05') AND day<= date('2019-07-04'),
AVG(amount) AS avg_amt2
WHERE day >= date('2019-07-05') AND day<= date('2019-09-04')
1
  • I would like to repeat but for a different time period for comparison Commented Nov 18, 2020 at 15:39

1 Answer 1

3

You can use the FILTER clause to aggregate functions:

SELECT
    AVG(amount) FILTER(WHERE day >= date '2019-05-05' AND day <= date '2019-07-04') AS avg_amt1,
    AVG(amount) FILTER(WHERE day >= date '2019-07-05' AND day <= date '2019-09-04') AS avg_amt2
FROM table

We can optimize the query a little with a WHERE clause:

SELECT
    AVG(amount) FILTER(WHERE day <= date '2019-07-04') AS avg_amt1,
    AVG(amount) FILTER(WHERE day >= date '2019-07-05') AS avg_amt2
FROM table
WHERE day >= date '2019-05-05' AND day <= date '2019-09-04'
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.