Postgresql日期减去

时间:2015-10-12 10:02:22

标签: sql postgresql datetime

如何制作有效的请求,例如:

UPDATE b2c SET tranche = '18 - 25'
WHERE (dateofbirth::date BETWEEN NOW()::date - 18 'year' AND NOW()::date - 25 'year')

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

dateofbirth::date BETWEEN 
    (NOW() - interval '25 year')::date AND 
    (NOW() - interval '18 year')::date

答案 1 :(得分:1)

您可以使用Postgres演员语法:

UPDATE b2c SET tranche = '18 - 25'
WHERE dateofbirth::date BETWEEN 
    NOW()::date - '25y'::interval AND 
    NOW()::date - '18y'::interval

答案 2 :(得分:1)

使用EXTRACT()Age()

select EXTRACT(year FROM age('1995-08-04'::date))::int age 

输出:

age
integer
--------
      20

所以你可以写 where 条件如下

UPDATE b2c SET tranche = '18 - 25'
WHERE EXTRACT(year FROM age(dateofbirth))::int >=18 
 AND  EXTRACT(year FROM age(dateofbirth))::int <=25