【问题标题】:how to create a new field to show, together with the SELECT'ed fields?如何创建一个新字段来显示,以及选择的字段?
【发布时间】:2016-10-30 15:13:46
【问题描述】:

这些代码行过滤所有 50 岁以上的人。

SELECT birthday FROM table_name
WHERE birthday < now() - '50 years'::interval

除此之外,我还需要创建一个额外的列,显示实际年龄。

Es.

  birthday     age
 2000-06-28    16

“年龄”列应与 SELECT 一起创建。它不在表中。

【问题讨论】:

    标签: sql postgresql select


    【解决方案1】:

    我已经解决了。

    SELECT birthday , extract (day from((now() - birthday)/365)) as age
    FROM table_name
    WHERE birthday < now() - '50 years'::interval
    

    【讨论】:

      【解决方案2】:

      您可以使用名为age()的特定函数

      SELECT EXTRACT(year FROM age(birth_date)) AS age FROM ...
      

      https://www.postgresql.org/docs/9.5/static/functions-datetime.html

      记住:age 从 current_date 中减去(午夜

      【讨论】:

      • 我尝试使用 SELECTbirthday, 2016 - EXTRACT(year FROM (birthday)) 作为 age ,但它不计算出生月份。所以不是所有的年龄都是正确的。
      • @Marco 你说的it does not count the month of birth是什么意思?
      • 它给了我所有 49 个年龄。
      • @Marco 这是因为age 从 current_date 中减去(在午夜)。所以你可以做下一步来修复它select EXTRACT(year FROM age(NOW(), NOW() - '50 years'::interval)) AS age;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2023-02-08
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多