如何在postgres中创建ISO-8601格里高利日期表

时间:2015-04-24 04:20:45

标签: sql postgresql sql-date-functions

我希望在postgres数据库中创建日期表。 样本数据预计如下所示:

date key = 00001
calendar_date= 1/1/2015
week_num= 1
month_num= 1
month_name= Jan
quarter_num= 1
calendar_year= 2015
iso_dayofweek= 4
dayofweek_name= Thursday

是否有一个函数或SQL我可以帮助创建日期格里高利ISO-8601表?
我希望自动生成这个,如果可能的话。在这方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

见下面的例子

CREATE TABLE Addresses(
    Id SERIAL NOT NULL PRIMARY KEY,
    UserId int NULL,
    City varchar(50) NULL,
    State varchar(50) NULL,
    CountryCode varchar(50) NULL,
    PostalCode varchar(50) NULL,
    Street1 varchar(50) NULL,
    Street2 varchar(50) NULL
);

结果:

SELECT mydate calendar_date
    ,EXTRACT(WEEK FROM mydate) week_num
    ,EXTRACT(month FROM mydate) month_num
    ,to_char(mydate,'Mon') month_name
    ,EXTRACT(Quarter FROM mydate) quarter_num
    ,EXTRACT(year FROM mydate) calendar_year
    ,EXTRACT(DOW FROM mydate) iso_dayofweek
    ,to_char(mydate, 'day') dayofweek_name
FROM (
    SELECT now()::DATE mydate
    ) t

您可以使用calendar_date week_num month_num month_name quarter_num calendar_year iso_dayofweek dayofweek_name ------------- -------- --------- ---------- ----------- ------------- ------------- -------------- 2015/04/24 17 4 Apr 2 2015 5 friday 获取一年中的所有日期:generate_series()

2015

这将从select generate_series(0,364) + date'1/1/2015' 生成日期,并在给定示例中使用此选择而不是1/1/2015 - 31/12/2015

如果要为年份SELECT now()::DATE创建表格,则可以使用以下查询

2015

,表格看起来像CREATE TABLE mycal_2015 AS SELECT row_number() OVER () date_key ,mydate calendar_date ,EXTRACT(WEEK FROM mydate) week_num ,EXTRACT(month FROM mydate) month_num ,to_char(mydate,'Mon') month_name ,EXTRACT(Quarter FROM mydate) quarter_num ,EXTRACT(year FROM mydate) calendar_year ,EXTRACT(DOW FROM mydate) iso_dayofweek ,to_char(mydate, 'day') dayofweek_name FROM ( SELECT generate_series(0, 364) + DATE '1/1/2015' mydate ) t

select * from mycal_2015

POSTGRESQL:提取功能

PostgreSQL提取功能从日期中提取部件

语法:date_key calendar_date week_num month_num month_name quarter_num calendar_year iso_dayofweek dayofweek_name -------- ------------- -------- --------- ---------- ----------- ------------- ------------- -------------- 1 2015/01/01 1 1 Jan 1 2015 4 thursday 2 2015/01/02 1 1 Jan 1 2015 5 friday 3 2015/01/03 1 1 Jan 1 2015 6 saturday 4 2015/01/04 1 1 Jan 1 2015 0 sunday 5 2015/01/05 2 1 Jan 1 2015 1 monday 6 2015/01/06 2 1 Jan 1 2015 2 tuesday ... . . . 364 2015/12/30 53 12 Dec 4 2015 3 wednesday 365 2015/12/31 53 12 Dec 4 2015 4 thursday

  

日期是日期,日期,时间戳,时间或间隔值   部分将被提取。

     

单位是日,月,分的间隔的单位类型,   小时等等

它可以是以下之一:

extract( unit from date )

注意:Extract函数适用于PostgreSQL版本8.4及更高版本

Date/Time Functions and Operators
generate_series()