如何在PostgreSQL中找到最早的日期?

时间:2017-12-08 15:23:51

标签: sql postgresql date

我正在使用Postgres表,该表有一个名为first_contact_date的字段,其类型为date。我正在使用约会的the mm/dd/yyyy representation。 我的查询在编写时正常工作,但按月按字面顺序排序。

SELECT first_contact_date 
FROM schema.table 
ORDER BY first_contact_date

例如“10/3/2016”将在“1/2/2017”之后,即使在日期意义上,它应该是“1/2 / 2017”,这是在“2016年10月3日”之后

我看了

  1. How to find the earliest and latest date from a database,但它太模糊了,我已经在使用订单了。
  2. SQL ordering by earliest date in group,但我使用的格式不同。
  3. How do I return the record with the earliest date?,同上,编号为2
    1. PostgreSQL query where date oldest,但这限制为一年
    2. 如何构建查询以便返回日历透视图中的最早日期?

1 个答案:

答案 0 :(得分:1)

您可以从年初开始提取间隔并按顺序排序:

SELECT first_contact_date-date_trunc('year',first_contact_date), first_contact_date
FROM schema.table 
ORDER BY 1;

编辑:漫长的岁月可能无法正常工作,因为从年初开始的持续时间可能会在2月之后有所不同。

这有点脏,但也可以长时间正常工作:

    SELECT to_char(first_contact_date,'MM')::int*100+to_char(first_contact_date,'DD')::int datenum
FROM schema.table 
ORDER BY 1;