【问题标题】:Difference in years between two dates两个日期之间的年差
【发布时间】:2015-06-13 04:15:33
【问题描述】:

我在 postgresql 中有一个表,它有一个名为 birthdate 的列数据类型 TIMESTAMP,是否可以编写一个 sql 语句来返回表中存储的生日与年份的差异当前日期?这将如何完成?我的服务器是 Postgresql

这是我尝试过的,但在第二次选择时出现语法错误

select DATEDIFF(yy, NOW(), select birthdate from match where match_id = '550856d8560a64ed180416d1556f5435f4bb054c68930040')

【问题讨论】:

    标签: sql postgresql date


    【解决方案1】:

    这里有很多问题。

    select DATEDIFF
           ^^^^
           PostgreSQL doesn't have a datediff function.
    
    regress-> \df datediff
                           List of functions
     Schema | Name | Result data type | Argument data types | Type 
    --------+------+------------------+---------------------+------
    (0 rows)
    

    我认为您需要 - 运算符、extract 函数、justify_intervalto_char 函数。另外,写current_timestamp而不是now(),这是标准拼写。

    还有这个:

    (yy, NOW(), select birthdate ...)
                ^^^
    

    是语法错误,因为您没有将子查询包装在(parentheses) 中,应该是:

    (yy, NOW(), (select birthdate  ...))
    

    但在这种情况下,不需要子查询,因为您可以将其展平到外部查询中,当子查询已修复但没有其他内容时,它会为您提供:

    select DATEDIFF(yy, NOW(), birthdate)
    from match where match_id = '550856d8560a64ed180416d1556f5435f4bb054c68930040';
    

    对于日期减法:

    regress=> SELECT extract(year FROM justify_interval(current_timestamp - DATE '2008-02-01'));
     date_part 
    -----------
             7
    (1 row)
    

    给出类似的东西:

    SELECT extract(year FROM justify_interval(current_timestamp - birthdate))
    from match where match_id = '550856d8560a64ed180416d1556f5435f4bb054c68930040';
    

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 2022-10-02
      • 2013-07-17
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多