Get month name from number in PostgreSQL

前端 未结 2 1314
悲&欢浪女
悲&欢浪女 2021-02-07 00:32

I have a table with a column month(integer). In this column I store values like 1, 2, .. 12.
But I have to show the month name

相关标签:
2条回答
  • 2021-02-07 00:46

    There might be a quicker answer, but it seems to be possible by:

    • Turning your int into a string
    • Reading that string as a timestamp
    • Displaying the month of the timestamp.

    For example:

    select to_char(to_timestamp(to_char(4, '999'), 'MM'), 'Mon')
    

    returns 'Apr'.

    You can turn it into a function:

    create function to_month(integer) returns varchar as
    $$
        select to_char(to_timestamp(to_char($1, '999'), 'MM'), 'Mon');
    $$ language sql
    

    and use it throughout your code.

    select to_month(month_column) from mytable
    
    0 讨论(0)
  • 2021-02-07 01:08

    Basically what @small_duck already posted, but a couple of improvements:

    SELECT to_char(to_timestamp (4::text, 'MM'), 'TMmon')
    
    • A plain cast to text 4::text is enough, no need for to_char(..).

    • Question asks for lower case "jan", there is a template pattern for that: mon.

    • If you want to localize the output, prefix the template with the modifier TM.

    0 讨论(0)
提交回复
热议问题