I am working with a Postgres table that has a field named first_contact_date
where it is of type date. I am using the the mm/dd/yyyy representation of a date. My query works correctly as written but it orders literally by month.
SELECT first_contact_date
FROM schema.table
ORDER BY first_contact_date
For example "10/3/2016" would go after "1/2/2017", even though in a date sense, it should be "1/2/2017" that goes after "10/3/2016".
I have looked at
and
How to I structure the query so that the earliest date from a calendar perspective is returned?
You can extract interval starting from beginning of year and order by it:
SELECT first_contact_date-date_trunc('year',first_contact_date), first_contact_date
FROM schema.table
ORDER BY 1;
Edit: Long years might not work properly as duration starting from begining of year might differ after February.
This is a bit dirty, but will work correctly also for long years:
SELECT to_char(first_contact_date,'MM')::int*100+to_char(first_contact_date,'DD')::int datenum
FROM schema.table
ORDER BY 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.