Reputation: 1342
I want to display data from a table sorted on the month in 'Jan', 'Feb' format. If I use to_char function, the sorting won't be correct. How can this be done? Sample data and query I am trying.
SELECT * FROM tb;
dt
------------
2014-12-12
2014-01-01
SELECT to_char(dt,'Mon') FROM tb ORDER BY to_char(dt,'Mon');
to_char
---------
Dec
Jan
Upvotes: 1
Views: 2431
Reputation: 1
I had the same problem and I couldn't order by dt because I had an error
ORDER BY expressions must appear in select list.
I did the following:
SELECT mon
FROM (SELECT DISTINCT DATE_PART('MONTH', dt) AS m, TO_CHAR(dt,'Mon') AS mon FROM tb) AS mname
ORDER BY m;
I used DISTINCT to avoid repeated months.
Upvotes: 0
Reputation: 37023
You need to order by date and display month as per the date. Try something like:
SELECT TO_CHAR(dt,'Mon')
FROM tb
ORDER BY dt
Upvotes: 2