使用SQL填充多年份日历表

huangapple go评论89阅读模式
英文:

Populating Multi-Year Calendar Table using SQL

问题

我想填充一个多年份的日历表,并根据日期计算多个字段的值。我正在在Postgres上运行这个脚本,即使我将start_date设置为2023-02-16,end_date设置为2023-02-17,它运行起来也非常慢。请帮助找出问题所在。

英文:

I want to populate a multi-year calendar table and calculate the value of multiple fields based on the date. I'm running this script on Postgres, it is taking forever to run even if I pass start_date as 2023-02-16 and end_date as 2023-02-17. Please help with what is wrong here.

使用SQL填充多年份日历表

答案1

得分: 0

使用generate_series()的示例:

INSERT INTO t1(....)
SELECT 
    (g.d)::date AS 日期,
    EXTRACT(year FROM g.d) AS ,
    EXTRACT(month FROM g.d) AS ,
    EXTRACT(day FROM g.d) AS ,
    EXTRACT(quarter FROM g.d) AS 季度,
    EXTRACT(week FROM g.d) AS ,
    EXTRACT(isodow FROM g.d) AS ISO星期,
    EXTRACT(doy FROM g.d) AS 年内天数,
    EXTRACT(isoyear FROM g.d) AS ISO年
   FROM generate_series('1970-01-01 00:00:00'::timestamp without time zone, '2049-12-31 00:00:00'::timestamp without time zone, '1 day'::interval) g(d)
 ORDER BY g.d;

只需更改表名t1和您需要的列。在我的笔记本电脑上,生成和插入29220个日期只需0.1秒。

英文:

Example using generate_series():

INSERT INTO t1(....)
SELECT 
    (g.d)::date AS date,
    EXTRACT(year FROM g.d) AS year,
    EXTRACT(month FROM g.d) AS month,
    EXTRACT(day FROM g.d) AS day,
    EXTRACT(quarter FROM g.d) AS quarter,
    EXTRACT(week FROM g.d) AS week,
    EXTRACT(isodow FROM g.d) AS isodow,
    EXTRACT(doy FROM g.d) AS doy,
    EXTRACT(isoyear FROM g.d) AS isoyear
   FROM generate_series('1970-01-01 00:00:00'::timestamp without time zone, '2049-12-31 00:00:00'::timestamp without time zone, '1 day'::interval) g(d)
 ORDER BY g.d;

Just change the table name t1 and the columns you need. It take 0.1 second on my laptop to generate and insert 29220 dates.

huangapple
  • 本文由 发表于 2023年2月27日 18:05:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定