SQL 从 PostgreSQL 中的数字获取月份名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9094392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:12:44  来源:igfitidea点击:

Get month name from number in PostgreSQL

sqlpostgresqldate

提问by user007

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.

我有一个带有列month( integer)的表。在这一列中,我存储了诸如1, 2, .. 12.
但我必须显示月份名称

Ex: If the value is 1I need to display jan.

例如:如果值是1我需要显示jan.

回答by Erwin Brandstetter

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::textis enough, no need for to_char(..).

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

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

  • 简单的文本转换4::text就足够了,不需要to_char(..).

  • 问题问的小写的“扬”,有一个模板模式为:mon

  • 如果要本地化输出,请在模板前加上修饰符TM

回答by small_duck

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.
  • 把你的 int 变成一个字符串
  • 将该字符串作为时间戳读取
  • 显示时间戳的月份。

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(, '999'), 'MM'), 'Mon');
$$ language sql

and use it throughout your code.

并在整个代码中使用它。

select to_month(month_column) from mytable