维度表(Dimension Table)是数据仓库中的一个重要组成部分,主要用于存储描述性属性,这些属性通常用于查询分析和报表生成。维度表与事实表(Fact Table)配合使用,事实表存储业务过程的度量值,而维度表提供这些度量值的上下文信息。
维度表可以分为以下几种类型:
维度表广泛应用于各种数据分析和报表生成场景,如销售分析、客户分析、库存分析等。
以下是一个简单的示例,展示如何在MySQL中创建一个时间维度表:
CREATE TABLE time_dimension (
time_id INT PRIMARY KEY AUTO_INCREMENT,
date DATE NOT NULL,
year INT NOT NULL,
quarter INT NOT NULL,
month INT NOT NULL,
day INT NOT NULL,
day_of_week VARCHAR(10) NOT NULL
);
-- 插入数据
INSERT INTO time_dimension (date, year, quarter, month, day, day_of_week)
SELECT
DATE_ADD('2000-01-01', INTERVAL n DAY) AS date,
YEAR(DATE_ADD('2000-01-01', INTERVAL n DAY)) AS year,
QUARTER(DATE_ADD('2000-01-01', INTERVAL n DAY)) AS quarter,
MONTH(DATE_ADD('2000-01-01', INTERVAL n DAY)) AS month,
DAY(DATE_ADD('2000-01-01', INTERVAL n DAY)) AS day,
DAYNAME(DATE_ADD('2000-01-01', INTERVAL n DAY)) AS day_of_week
FROM (
SELECT a.N + b.N * 10 + c.N * 100 AS n
FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
CROSS JOIN (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
CROSS JOIN (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) c
) numbers
WHERE DATE_ADD('2000-01-01', INTERVAL n DAY) <= '2023-12-31';
通过以上步骤和示例,你可以成功创建一个维度表,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云