缓慢变化维度(SCD)查询

SQL查询入门SQL

问题

查询客户历史数据,使用SCD Type 2维度表获取特定时间点的客户属性。

答题要点

-- SCD Type 2 维度表结构
-- dim_customer: customer_key, customer_id, customer_name, segment, region,
--               effective_date, expiry_date, is_current

-- 查询1: 获取当前有效的客户信息
SELECT
    customer_key,
    customer_id,
    customer_name,
    segment,
    region
FROM dim_customer
WHERE is_current = 1;

-- 查询2: 获取特定日期(如2023-06-15)时有效的客户信息
SELECT
    customer_key,
    customer_id,
    customer_name,
    segment,
    region,
    effective_date,
    expiry_date
FROM dim_customer
WHERE customer_id = 'C001'
  AND effective_date <= '2023-06-15'
  AND (expiry_date > '2023-06-15' OR expiry_date IS NULL)
ORDER BY effective_date DESC;

-- 查询3: 关联历史销售数据,使用订单日期匹配正确的客户版本
SELECT
    fs.order_date,
    fs.order_id,
    dc.customer_name,
    dc.segment AS customer_segment_at_order_time,
    dc.region AS customer_region_at_order_time,
    fs.sales_amount
FROM fact_sales fs
INNER JOIN dim_customer dc
    ON fs.customer_id = dc.customer_id
    AND fs.order_date >= dc.effective_date
    AND (fs.order_date < dc.expiry_date OR dc.expiry_date IS NULL)
WHERE fs.order_date >= '2023-01-01'
ORDER BY fs.order_date;

-- 查询4: 客户属性变更历史追踪
SELECT
    customer_id,
    customer_name,
    segment,
    region,
    effective_date,
    expiry_date,
    DATEDIFF(COALESCE(expiry_date, CURDATE()), effective_date) AS days_in_status,
    LAG(segment) OVER (PARTITION BY customer_id ORDER BY effective_date) AS previous_segment,
    CASE
        WHEN LAG(segment) OVER (PARTITION BY customer_id ORDER BY effective_date) IS NULL THEN '新建'
        WHEN segment != LAG(segment) OVER (PARTITION BY customer_id ORDER BY effective_date) THEN '变更'
        ELSE '无变化'
    END AS change_type
FROM dim_customer
WHERE customer_id = 'C001'
ORDER BY effective_date;

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题