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.
我有一个包含一个列月(整数)的表。在这一列中,我存储1、2之类的值。12。但是我必须显示月份的名称。
Ex: If the value is 1
I need to display jan
.
如果值是1,我需要显示jan。
2 个解决方案
#1
26
Basically what @small_duck already posted, but a couple of improvements:
基本上@small_duck已经发布了什么,但是有几个改进:
SELECT to_char(to_timestamp (4::text, 'MM'), 'TMmon')
-
A plain cast to text
4::text
is enough, no need forto_char(..)
.文本4:::文本就足够了,不需要to_char(..)。
-
Question asks for lower case "jan", there is a template pattern for that:
mon
.问一个小写“jan”的问题,有一个模板模式:mon。
-
If you want to localize the output, prefix the template with the modifier
TM
.如果要本地化输出,请在模板前面加上修饰符TM。
#2
6
There might be a quicker answer, but it seems to be possible by:
也许会有更快的答案,但似乎是有可能的:
- Turning your int into a string
- 将int类型转换为字符串
- 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'.
返回“4月”。
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
#1
26
Basically what @small_duck already posted, but a couple of improvements:
基本上@small_duck已经发布了什么,但是有几个改进:
SELECT to_char(to_timestamp (4::text, 'MM'), 'TMmon')
-
A plain cast to text
4::text
is enough, no need forto_char(..)
.文本4:::文本就足够了,不需要to_char(..)。
-
Question asks for lower case "jan", there is a template pattern for that:
mon
.问一个小写“jan”的问题,有一个模板模式:mon。
-
If you want to localize the output, prefix the template with the modifier
TM
.如果要本地化输出,请在模板前面加上修饰符TM。
#2
6
There might be a quicker answer, but it seems to be possible by:
也许会有更快的答案,但似乎是有可能的:
- Turning your int into a string
- 将int类型转换为字符串
- 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'.
返回“4月”。
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