📅  最后修改于: 2023-12-03 14:43:39.843000             🧑  作者: Mango
Kimball 数据仓库 SQL Calendar - SQL 是由 Ralph Kimball 创立的数据仓库设计方法论的一部分。该方法论通过提供一种 SQL 版本的日历表,使得开发人员可以更方便地在数据仓库中查询和分析时间相关的数据。该方法论广泛应用于企业级数据仓库的设计与实现中。
Kimball 数据仓库 SQL Calendar - SQL 所提供的日历表是一个具有连续的日期范围的表。每一行代表一个特定的日期,如下所示:
| date | year | month | quarter | week | day | day_name | is_holiday | |:----------:|:----:|:-----:|:-------:|:----:|:---:|:--------:|:----------:| | 2021-01-01 | 2021 | 1 | 1 | 1 | 1 | Friday | Y | | 2021-01-02 | 2021 | 1 | 1 | 1 | 2 | Saturday | N | | 2021-01-03 | 2021 | 1 | 1 | 1 | 3 | Sunday | N | | ... | ... | ... | ... | ... | ... | ... | ... |
日历表可以通过以下 SQL 语句生成:
WITH RECURSIVE calendar AS (
SELECT DATE('now', 'start of year') as date,
strftime('%Y', DATE('now', 'start of year')) as year,
strftime('%m', DATE('now', 'start of year')) as month,
CASE
WHEN strftime('%m', DATE('now', 'start of year')) IN ('01', '02', '03') THEN '1'
WHEN strftime('%m', DATE('now', 'start of year')) IN ('04', '05', '06') THEN '2'
WHEN strftime('%m', DATE('now', 'start of year')) IN ('07', '08', '09') THEN '3'
WHEN strftime('%m', DATE('now', 'start of year')) IN ('10', '11', '12') THEN '4'
END as quarter,
strftime('%W', date) as week,
strftime('%d', date) as day,
strftime('%A', date) as day_name,
CASE
WHEN strftime('%w', date) IN ('0', '6') THEN 'Y'
ELSE 'N'
END as is_holiday
FROM (
SELECT
ROW_NUMBER() OVER() - 1 n
FROM
sqlite_master
LIMIT 10000
)
WHERE n <= julianday('now', 'start of year', '+1 year') - julianday('now', 'start of year', 'utc') + 1
UNION ALL
SELECT date(date, '+1 day'),
strftime('%Y', date(date, '+1 day')) as year,
strftime('%m', date(date, '+1 day')) as month,
CASE
WHEN strftime('%m', date(date, '+1 day')) IN ('01', '02', '03') THEN '1'
WHEN strftime('%m', date(date, '+1 day')) IN ('04', '05', '06') THEN '2'
WHEN strftime('%m', date(date, '+1 day')) IN ('07', '08', '09') THEN '3'
WHEN strftime('%m', date(date, '+1 day')) IN ('10', '11', '12') THEN '4'
END as quarter,
strftime('%W', date(date, '+1 day')) as week,
strftime('%d', date(date, '+1 day')) as day,
strftime('%A', date(date, '+1 day')) as day_name,
CASE
WHEN strftime('%w', date(date, '+1 day')) IN ('0', '6') THEN 'Y'
ELSE 'N'
END as is_holiday
FROM calendar
WHERE date < DATE('now', '+1 year')
)
SELECT * FROM calendar;
生成日历表后,可以通过与实际业务数据的关联,轻松地实现时间框架下的数据分析和报表开发。例如,以下 SQL 语句可以查询所有 2021 年工作日的销售额:
SELECT sum(sales) AS total_sales
FROM sales_fact
INNER JOIN calendar ON sales_fact.date_key = calendar.date
WHERE calendar.year = '2021' AND calendar.is_holiday = 'N'
Kimball 数据仓库 SQL Calendar - SQL 提供了一种灵活而有效的方式来在数据仓库中处理时间框架问题,特别是在报表开发和数据分析方面。总的来说,这种方法论相当实用,并已成为许多企业级数据仓库设计的必备工具。