且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

生成日期范围的数据,包括数据中不存在的数据

更新时间:2023-01-29 15:30:04

辅助日历表可以正常运行。最简单的日历表是​​单列日期。

An auxiliary calendar table will work well. The simplest possible calendar table is a single column of dates.

create table calendar (
    cal_date date primary key
);

您可以使用电子表格或SQL来填充它。其上的外连接将带来数据中不存在的日期。限制GRANT和REVOKE的权限,并使用任何必要的手段确保您期望在其中的日期实际上在那里。我在我的服务器上运行一个日常报告,确保有n行,并验证最早和最新的日期。

You can use a spreadsheet or SQL to populate it. An outer join on it will bring in the dates that don't exist in your data. Limit permissions with GRANT and REVOKE, and use whatever means necessary to make sure that the dates you expect to be in there are actually in there. I run a daily report on my server that makes sure there are 'n' rows, and verifies the earliest and latest dates.

在某些平台上,您可以生成一个系列的日期,并直接或在CTE中使用。 PostgreSQL有这样的功能;我不知道MySQL是不是。但是,如果你想自己滚动,他们不难写。

On some platforms, you can generate a series of dates on the fly, and either use it directly or in a CTE. PostgreSQL has functions for that; I don't know whether MySQL does. They're not hard to write, though, if you want to roll your own.