【问题标题】:What is the datatype of Months(only months) in postgres?postgres 中 Months(only months) 的数据类型是什么?
【发布时间】:2015-04-22 00:23:20
【问题描述】:

我需要在 postgresql 中创建一个名为“months”的列的表。“Month”列应该有 January、 February 等而不是 1、2,3 等。我需要检索按月份排序的数据.我应该使用什么数据类型,如何检索按月排序的数据?

【问题讨论】:

  • 最好将数字存储起来,然后在向最终用户显示数据时将它们转换为名称。如果您存储 January,您将无法使用非英语语言环境运行您的应用程序
  • @a_horse_with_no_name 是的,这很好,我尝试过你的建议,但就我而言,我做不到。

标签: postgresql


【解决方案1】:

如果您只需要保存几个月而不是整个日期,我会创建一个enum

CREATE TYPE month_enum AS ENUM
('January', 
 'February',
 'March', 
 'April',
 'May',
 'June',
 'July',
 'August',
 'September',
 'October',
 'November',
 'December'
);

【讨论】:

  • @Mureinnik 你的答案是正确的。我可以将日期类型(month_enum)更改为字符吗?我需要将日期转换为一张表到另一张表。其他表月份列数据类型为字符。
  • @Pirinthan 你可以使用:: 操作符来转换它:SELECT month_col::varchar FROM my_table
【解决方案2】:

最好将月份保存为整数,并在查询时显示月份名称:

with months(month) as (
    select generate_series(1, 12)
)
select
    month as month_number,
    to_char(
        '1999-12-31'::date + month * interval '1 month',
        'Month'
    ) as month_name
from months
order by month_number; -- or by month_name
 month_number | month_name 
--------------+------------
            1 | January  
            2 | February 
            3 | March    
            4 | April    
            5 | May      
            6 | June     
            7 | July     
            8 | August   
            9 | September
           10 | October  
           11 | November 
           12 | December 

为了便于构建查询,请创建一个返回月份名称的函数:

create or replace function month_name(month integer)
returns text as $$
select
    to_char(
        '1999-12-31'::date + month * interval '1 month',
        'Month'
    );
$$ language sql;

现在很简单:

with months(month) as (
    select generate_series(1, 12)
)
select
    month as month_number,
    month_name(month)
from months
order by month_number;

【讨论】:

    【解决方案3】:

    根据您的要求,您有几个选择,具体取决于您的需要:

    • 如果您只需要 Months 作为静态记录,但实际上并不需要时间,则可以使用枚举,正如 Mureinik 回答的那样,
    • 如果您需要将月份作为特定时间的一部分,您可以使用datetime

    假设您使用 ENUM,您可以使用 SELECT * FROM "Month" ORDER BY id ASC

    a_horse_with_no_name 确实有一点说,由于本地化问题,最好使用数月的数值。您可以将 Month 作为不同语言的不同月份名称的单独表格,但可能有更有效的方法来做到这一点。或者,可以有每个月的号码,并且在查询时,您可以根据建议的项目中的号码来调用月份的名称。这样您就可以根据本地化调用不同的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-14
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 2017-05-10
      • 2023-04-10
      相关资源
      最近更新 更多