-- ============================================
-- 跨境电商数据分析竞赛 - 任务二:数据查询操作
-- 业务查询SQL脚本集合
-- ============================================

USE ecommerce_analysis;

-- ============================================
-- 一、基础查询
-- ============================================

-- 1.1 查询各产品类别的总销售额和销售量
SELECT 
    category AS 产品类别,
    COUNT(DISTINCT order_id) AS 订单数量,
    SUM(quantity) AS 销售数量,
    ROUND(SUM(total_amount), 2) AS 总销售额_美元,
    ROUND(AVG(total_amount), 2) AS 平均订单金额_美元,
    ROUND(SUM(profit), 2) AS 总利润_美元
FROM v_sales_detail
GROUP BY category
ORDER BY 总销售额_美元 DESC;

-- 1.2 查询各区域的销售排名
SELECT 
    region AS 销售区域,
    COUNT(DISTINCT country) AS 国家数量,
    COUNT(DISTINCT order_id) AS 订单数量,
    SUM(quantity) AS 销售数量,
    ROUND(SUM(total_amount), 2) AS 总销售额_美元,
    ROUND(AVG(total_amount), 2) AS 平均订单金额_美元,
    RANK() OVER (ORDER BY SUM(total_amount) DESC) AS 销售排名
FROM v_sales_detail
GROUP BY region
ORDER BY 销售排名;

-- 1.3 查询top20畅销产品及其销售指标
SELECT 
    product_id AS 产品编号,
    product_name AS 产品名称,
    category AS 产品类别,
    COUNT(DISTINCT order_id) AS 订单数量,
    SUM(quantity) AS 销售数量,
    ROUND(SUM(total_amount), 2) AS 总销售额_美元,
    ROUND(AVG(unit_price), 2) AS 平均单价_美元,
    ROUND(SUM(profit), 2) AS 总利润_美元,
    ROUND(SUM(CASE WHEN is_returned THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS 退货率_百分比
FROM v_sales_detail
GROUP BY product_id, product_name, category
ORDER BY 总销售额_美元 DESC
LIMIT 20;

-- ============================================
-- 二、复杂查询
-- ============================================

-- 2.1 查询各类别产品的平均库存周转率(销售量/平均库存量)
SELECT 
    category AS 产品类别,
    SUM(quantity) AS 总销售量,
    ROUND(AVG(stock_quantity), 2) AS 平均库存量,
    ROUND(SUM(quantity) * 1.0 / AVG(stock_quantity), 4) AS 库存周转率,
    CASE 
        WHEN SUM(quantity) * 1.0 / AVG(stock_quantity) > 0.015 THEN '高周转'
        WHEN SUM(quantity) * 1.0 / AVG(stock_quantity) > 0.008 THEN '中周转'
        ELSE '低周转'
    END AS 周转评级
FROM v_sales_detail
GROUP BY category
ORDER BY 库存周转率 DESC;

-- 2.2 查询各区域各品类的销售占比
SELECT 
    region AS 区域,
    category AS 品类,
    ROUND(SUM(total_amount), 2) AS 销售额_美元,
    ROUND(SUM(total_amount) * 100.0 / SUM(SUM(total_amount)) OVER (PARTITION BY region), 2) AS 区域内占比_百分比,
    ROUND(SUM(total_amount) * 100.0 / SUM(SUM(total_amount)) OVER (), 2) AS 总体占比_百分比
FROM v_sales_detail
GROUP BY region, category
ORDER BY region, 销售额_美元 DESC;

-- 2.3 查询新品(上架3个月内)的存活率和销售表现
WITH product_performance AS (
    SELECT 
        p.product_id,
        p.product_name,
        p.category,
        p.product_launch_date,
        DATEDIFF(MAX(s.order_date), p.product_launch_date) AS 在售天数,
        COUNT(DISTINCT s.order_id) AS 订单数量,
        SUM(s.quantity) AS 销售数量,
        ROUND(SUM(s.total_amount), 2) AS 销售额_美元,
        CASE 
            WHEN DATEDIFF(MAX(s.order_date), p.product_launch_date) >= 90 THEN '存活'
            ELSE '下架风险'
        END AS 存活状态
    FROM dim_product p
    LEFT JOIN fact_sales s ON p.product_id = s.product_id
    WHERE p.product_launch_date >= DATE_SUB((SELECT MAX(order_date) FROM fact_sales), INTERVAL 3 MONTH)
    GROUP BY p.product_id, p.product_name, p.category, p.product_launch_date
)
SELECT 
    category AS 产品类别,
    COUNT(*) AS 新品数量,
    SUM(CASE WHEN 存活状态 = '存活' THEN 1 ELSE 0 END) AS 存活数量,
    ROUND(SUM(CASE WHEN 存活状态 = '存活' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS 存活率_百分比,
    ROUND(AVG(销售额_美元), 2) AS 平均销售额_美元,
    ROUND(AVG(订单数量), 2) AS 平均订单数
FROM product_performance
GROUP BY category
ORDER BY 存活率_百分比 DESC;

-- 2.4 查询退货率top10产品及其特征
SELECT 
    product_id AS 产品编号,
    product_name AS 产品名称,
    category AS 产品类别,
    COUNT(*) AS 总订单数,
    SUM(CASE WHEN is_returned THEN 1 ELSE 0 END) AS 退货订单数,
    ROUND(SUM(CASE WHEN is_returned THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS 退货率_百分比,
    ROUND(AVG(unit_price), 2) AS 平均单价_美元,
    ROUND(AVG(delivery_days), 2) AS 平均配送天数,
    ROUND(AVG(discount_rate), 4) AS 平均折扣率
FROM v_sales_detail
GROUP BY product_id, product_name, category
HAVING COUNT(*) >= 10  -- 至少10笔订单
ORDER BY 退货率_百分比 DESC
LIMIT 10;

-- 2.5 查询各月度的销售趋势和同比环比增长率
WITH monthly_sales AS (
    SELECT 
        year AS 年份,
        month AS 月份,
        ROUND(SUM(total_amount), 2) AS 月销售额,
        COUNT(DISTINCT order_id) AS 月订单数
    FROM v_sales_detail
    GROUP BY year, month
)
SELECT 
    年份,
    月份,
    月销售额,
    月订单数,
    LAG(月销售额, 1) OVER (ORDER BY 年份, 月份) AS 上月销售额,
    ROUND((月销售额 - LAG(月销售额, 1) OVER (ORDER BY 年份, 月份)) * 100.0 / 
          LAG(月销售额, 1) OVER (ORDER BY 年份, 月份), 2) AS 环比增长率_百分比,
    LAG(月销售额, 12) OVER (ORDER BY 年份, 月份) AS 去年同期销售额,
    ROUND((月销售额 - LAG(月销售额, 12) OVER (ORDER BY 年份, 月份)) * 100.0 / 
          LAG(月销售额, 12) OVER (ORDER BY 年份, 月份), 2) AS 同比增长率_百分比
FROM monthly_sales
ORDER BY 年份, 月份;

-- 2.6 查询客户复购率和客户生命周期价值
WITH customer_metrics AS (
    SELECT 
        customer_id,
        COUNT(DISTINCT order_id) AS 购买次数,
        MIN(order_date) AS 首次购买日期,
        MAX(order_date) AS 最近购买日期,
        DATEDIFF(MAX(order_date), MIN(order_date)) AS 客户生命周期_天,
        SUM(total_amount) AS 总消费金额,
        AVG(total_amount) AS 平均订单金额
    FROM v_sales_detail
    GROUP BY customer_id
)
SELECT 
    CASE 
        WHEN 购买次数 = 1 THEN '单次购买'
        WHEN 购买次数 BETWEEN 2 AND 3 THEN '低频复购'
        WHEN 购买次数 BETWEEN 4 AND 6 THEN '中频复购'
        ELSE '高频复购'
    END AS 客户类型,
    COUNT(*) AS 客户数量,
    ROUND(AVG(购买次数), 2) AS 平均购买次数,
    ROUND(AVG(总消费金额), 2) AS 平均消费金额_美元,
    ROUND(AVG(客户生命周期_天), 2) AS 平均客户生命周期_天,
    ROUND(AVG(总消费金额 / NULLIF(客户生命周期_天, 0) * 365), 2) AS 年均消费金额_美元
FROM customer_metrics
GROUP BY 
    CASE 
        WHEN 购买次数 = 1 THEN '单次购买'
        WHEN 购买次数 BETWEEN 2 AND 3 THEN '低频复购'
        WHEN 购买次数 BETWEEN 4 AND 6 THEN '中频复购'
        ELSE '高频复购'
    END
ORDER BY 平均消费金额_美元 DESC;

-- ============================================
-- 三、聚合分析查询
-- ============================================

-- 3.1 产品类别和区域的交叉分析
SELECT 
    category AS 产品类别,
    region AS 销售区域,
    COUNT(DISTINCT order_id) AS 订单数,
    SUM(quantity) AS 销售量,
    ROUND(SUM(total_amount), 2) AS 销售额_美元,
    ROUND(AVG(unit_price), 2) AS 平均单价,
    ROUND(AVG(discount_rate), 4) AS 平均折扣率,
    RANK() OVER (PARTITION BY category ORDER BY SUM(total_amount) DESC) AS 类别内区域排名,
    RANK() OVER (PARTITION BY region ORDER BY SUM(total_amount) DESC) AS 区域内类别排名
FROM v_sales_detail
GROUP BY category, region
ORDER BY 产品类别, 销售额_美元 DESC;

-- 3.2 季度销售趋势分析
SELECT 
    year AS 年份,
    quarter AS 季度,
    category AS 产品类别,
    COUNT(DISTINCT order_id) AS 订单数,
    ROUND(SUM(total_amount), 2) AS 销售额_美元,
    ROUND(SUM(profit), 2) AS 利润_美元,
    ROUND(SUM(profit) * 100.0 / SUM(total_amount), 2) AS 利润率_百分比,
    ROUND(SUM(total_amount) * 100.0 / SUM(SUM(total_amount)) OVER (PARTITION BY year, quarter), 2) AS 类别占比_百分比
FROM v_sales_detail
GROUP BY year, quarter, category
ORDER BY year, quarter, 销售额_美元 DESC;

-- 3.3 促销效果分析
SELECT 
    CASE 
        WHEN discount_rate = 0 THEN '无折扣'
        WHEN discount_rate <= 0.1 THEN '1-10%折扣'
        WHEN discount_rate <= 0.2 THEN '11-20%折扣'
        WHEN discount_rate <= 0.3 THEN '21-30%折扣'
        ELSE '30%以上折扣'
    END AS 折扣区间,
    COUNT(DISTINCT order_id) AS 订单数,
    SUM(quantity) AS 销售量,
    ROUND(SUM(total_amount), 2) AS 销售额_美元,
    ROUND(AVG(total_amount), 2) AS 平均订单金额,
    ROUND(SUM(profit), 2) AS 利润_美元,
    ROUND(SUM(profit) * 100.0 / SUM(total_amount), 2) AS 利润率_百分比
FROM v_sales_detail
GROUP BY 折扣区间
ORDER BY FIELD(折扣区间, '无折扣', '1-10%折扣', '11-20%折扣', '21-30%折扣', '30%以上折扣');

-- 3.4 配送效率分析
SELECT 
    region AS 区域,
    ROUND(AVG(delivery_days), 2) AS 平均配送天数,
    ROUND(MIN(delivery_days), 2) AS 最短配送天数,
    ROUND(MAX(delivery_days), 2) AS 最长配送天数,
    ROUND(STDDEV(delivery_days), 2) AS 配送天数标准差,
    COUNT(CASE WHEN delivery_days <= 7 THEN 1 END) AS 一周内送达数,
    ROUND(COUNT(CASE WHEN delivery_days <= 7 THEN 1 END) * 100.0 / COUNT(*), 2) AS 一周内送达率_百分比,
    ROUND(AVG(shipping_cost), 2) AS 平均运费_美元
FROM v_sales_detail
GROUP BY region
ORDER BY 平均配送天数;

-- 3.5 价格敏感度分析
SELECT 
    category AS 产品类别,
    CASE 
        WHEN unit_price < 50 THEN '低价位(<50)'
        WHEN unit_price < 150 THEN '中低价位(50-150)'
        WHEN unit_price < 300 THEN '中高价位(150-300)'
        ELSE '高价位(>=300)'
    END AS 价格区间,
    COUNT(DISTINCT order_id) AS 订单数,
    SUM(quantity) AS 销售量,
    ROUND(SUM(total_amount), 2) AS 销售额_美元,
    ROUND(AVG(discount_rate), 4) AS 平均折扣率,
    ROUND(SUM(CASE WHEN is_returned THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 2) AS 退货率_百分比
FROM v_sales_detail
GROUP BY category, 价格区间
ORDER BY category, FIELD(价格区间, '低价位(<50)', '中低价位(50-150)', '中高价位(150-300)', '高价位(>=300)');

-- ============================================
-- 四、高级分析查询
-- ============================================

-- 4.1 使用窗口函数计算移动平均
WITH daily_sales AS (
    SELECT 
        order_date,
        SUM(total_amount) AS daily_amount
    FROM fact_sales
    GROUP BY order_date
)
SELECT 
    order_date AS 日期,
    daily_amount AS 当日销售额,
    ROUND(AVG(daily_amount) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS 7日移动平均,
    ROUND(AVG(daily_amount) OVER (ORDER BY order_date ROWS BETWEEN 29 PRECEDING AND CURRENT ROW), 2) AS 30日移动平均
FROM daily_sales
ORDER BY order_date
LIMIT 100;

-- 4.2 RFM客户分析
WITH customer_rfm AS (
    SELECT 
        customer_id,
        DATEDIFF((SELECT MAX(order_date) FROM fact_sales), MAX(order_date)) AS recency_days,
        COUNT(DISTINCT order_id) AS frequency,
        SUM(total_amount) AS monetary
    FROM fact_sales
    GROUP BY customer_id
),
rfm_scores AS (
    SELECT 
        customer_id,
        recency_days,
        frequency,
        monetary,
        NTILE(5) OVER (ORDER BY recency_days DESC) AS r_score,
        NTILE(5) OVER (ORDER BY frequency) AS f_score,
        NTILE(5) OVER (ORDER BY monetary) AS m_score
    FROM customer_rfm
)
SELECT 
    CASE 
        WHEN r_score >= 4 AND f_score >= 4 AND m_score >= 4 THEN '重要价值客户'
        WHEN r_score >= 4 AND f_score >= 3 THEN '重要发展客户'
        WHEN r_score <= 2 AND f_score >= 4 THEN '重要挽留客户'
        WHEN r_score <= 2 AND f_score <= 2 THEN '一般客户'
        ELSE '潜力客户'
    END AS 客户类型,
    COUNT(*) AS 客户数量,
    ROUND(AVG(recency_days), 2) AS 平均最近购买天数,
    ROUND(AVG(frequency), 2) AS 平均购买频次,
    ROUND(AVG(monetary), 2) AS 平均消费金额_美元
FROM rfm_scores
GROUP BY 客户类型
ORDER BY 平均消费金额_美元 DESC;

-- ============================================
-- 查询脚本说明
-- ============================================

/*
本脚本包含了竞赛任务二要求的所有查询类型:

基础查询 (3个):
- 产品类别销售统计
- 区域销售排名
- Top20畅销产品

复杂查询 (6个):
- 库存周转率分析
- 区域品类销售占比
- 新品存活率分析
- 退货率Top10分析
- 月度销售趋势及同环比
- 客户复购率和生命周期价值

聚合分析查询 (5个):
- 产品类别与区域交叉分析
- 季度销售趋势
- 促销效果分析
- 配送效率分析
- 价格敏感度分析

高级分析 (2个):
- 移动平均计算
- RFM客户分群

所有查询均可独立执行,结果可用于后续的数据可视化和报告撰写。
*/
