Count over previously defined alias

32 Views Asked by At

I'm trying to avoid writing twice the EXTRACT condition. There is any way to do that? Count over the previous alias apparently is not valid.

SELECT EXTRACT(DECADE FROM to_date(released_year::text, 'yyyy')) AS decade, 
    count(decade) AS total_by_decade
FROM album ...
1

There are 1 best solutions below

0
nbk On BEST ANSWER

Basically you can avoit it completely, but you can make a CTE

WITH
 CTE as(
SELECT EXTRACT(DECADE FROM to_date(released_year::text, 'yyyy')) AS decade 
 
FROM album ...)
SELECT  decade,  count(decade) AS total_by_decade FROM CTe GROUP BY decade