I have the following PostgreSQL query:
SELECT extract(YEAR from date), AVG(amount)
FROM transactions
GROUP BY extract(YEAR from date)
ORDER BY extract(YEAR from date)
How can I refactor the query so that extract(YEAR from date)
does not have to be repeated in the query?
3
Answers
I’m not sure if it is more readable or not, but you can refer to the output column ID:
Can use a common table expression.
This will create a CTE for you and then you can later, call it using
The main query selects the results from the CTE and orders them by
transaction_year
, doing this, you don’t need to repeat the extract(YEAR from date) expression in the main query and theyear_avg
CTE calculates the average amount for each year by extracting the year from the date column and grouping it.You can do it using subquery as follows :