如何在 PostgreSQL 的 WHERE 子句中使用我的计算参数的别名(在 SELECT 子句中)以防止重复?

How to use the alias of my calculated parameter (in SELECT clause) in WHERE clause with PostgreSQL to prevent repetition?

在下面的查询中,参数date_part('year', CURRENT_DATE) - f.birth_year重复了三次。我如何用别名 age 替换它?

SELECT
    date_part('year', CURRENT_DATE) - f.birth_year AS age
FROM
    public.foo f
WHERE
    date_part('year', CURRENT_DATE) - f.birth_year >=20 AND
    date_part('year', CURRENT_DATE) - f.birth_year <=30

您不能在 where 子句中重复使用 select 别名。您需要重复表达式,或使用子查询或 cte。

对于它的价值,您可以使用 between 使表达式在 where 子句中只出现一次而不是两次:

SELECT date_part('year', CURRENT_DATE) - f.birth_year AS age
FROM public.foo f
WHERE date_part('year', CURRENT_DATE) - f.birth_year BETWEEN 20 AND 30

至于子查询解决方案,那就是:

SELECT *
FROM (
    SELECT date_part('year', CURRENT_DATE) - f.birth_year AS age
    FROM public.foo
) f
WHERE age BETWEEN 20 AND 30

CTE 允许您命名表达式,这样您就可以避免重复它们。顺便说一句,这不是正确的年龄计算方法:

with data as (
    SELECT date_part('year', CURRENT_DATE) - birth_year AS age
    FROM public.foo
)
select * from data
WHERE age >= 20 AND <= 30;