0

在下面的查询中,该参数date_part('year', CURRENT_DATE) - f.birth_year重复了 3 次。我怎样才能用它的别名替换它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
4

2 回答 2

1

您不能在子句中重用select别名。where您需要重复表达式,或使用子查询或 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
于 2020-06-19T15:02:23.253 回答
0

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;
于 2020-06-19T16:18:19.610 回答