簡體   English   中英

postgres中幾個月(僅幾個月)的數據類型是什么?

[英]What is the datatype of Months(only months) in postgres?

我需要在postgresql中創建一個名為“months”的列的表。“Month”列應該有1月,2月等不是1,2,3等。我需要檢索按月排序的數據。 我應該使用什么數據類型以及如何檢索按月排序的數據?

如果你只需要保存月份,而不是整個日期,我會創建一個枚舉

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

最好將月份保存為整數,並在查詢時顯示月份名稱:

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;

根據您的要求,您可以根據需要選擇一些選項:

  • 如果你只需要幾個月作為靜態記錄,但你實際上並不需要時間,你可以使用枚舉,正如Mureinik回答的那樣,
  • 如果您需要將月份作為特定時間的一部分,則可以使用日期時間

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

a_horse_with_no_name確實有一個觀點,即由於本地化問題,最好使用數月的數值。 您可以使用不同語言為不同月份名稱創建月份單獨的表,但可能有更有效的方法。 或者,可以擁有每個月的數字,並且在查詢時,您可以根據建議的項目中的數字來調用月份的名稱。 這樣,您可以根據本地化調用其他名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM