数据仓库维度建模查询
SQL查询入门SQL数据建模数据仓库
问题
在星型模式数据仓库中查询销售数据,关联多个维度表进行分析。
答题要点
-- 星型模型查询:事实表 + 多个维度表
SELECT
dd.year,
dd.quarter,
dd.month_name,
dp.category AS product_category,
dp.subcategory AS product_subcategory,
dc.customer_segment,
dc.region AS customer_region,
ds.store_type,
ds.city AS store_city,
COUNT(DISTINCT fs.order_id) AS order_count,
SUM(fs.quantity) AS total_quantity,
SUM(fs.sales_amount) AS total_sales,
SUM(fs.profit_amount) AS total_profit,
ROUND(SUM(fs.profit_amount) * 100.0 / NULLIF(SUM(fs.sales_amount), 0), 2) AS profit_margin_pct,
ROUND(AVG(fs.sales_amount), 2) AS avg_order_value
FROM fact_sales fs
INNER JOIN dim_date dd ON fs.date_key = dd.date_key
INNER JOIN dim_product dp ON fs.product_key = dp.product_key
INNER JOIN dim_customer dc ON fs.customer_key = dc.customer_key
INNER JOIN dim_store ds ON fs.store_key = ds.store_key
WHERE dd.year IN (2023, 2024)
AND dp.category IN ('电子产品', '家居用品')
AND dc.customer_segment = '企业客户'
GROUP BY
dd.year,
dd.quarter,
dd.month_name,
dp.category,
dp.subcategory,
dc.customer_segment,
dc.region,
ds.store_type,
ds.city
HAVING SUM(fs.sales_amount) > 10000
ORDER BY dd.year DESC, dd.quarter DESC, total_sales DESC;
-- 带层级聚合(ROLLUP)
SELECT
dd.year,
dd.quarter,
dp.category,
SUM(fs.sales_amount) AS total_sales
FROM fact_sales fs
INNER JOIN dim_date dd ON fs.date_key = dd.date_key
INNER JOIN dim_product dp ON fs.product_key = dp.product_key
WHERE dd.year = 2024
GROUP BY dd.year, dd.quarter, dp.category WITH ROLLUP
ORDER BY dd.year, dd.quarter, dp.category;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题