# 创建月度收入数据用于演示
monthly_revenue = pd.DataFrame({
'month': ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06',
'2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12'],
'revenue': [850000, 920000, 880000, 950000, 990000, 1050000,
980000, 1020000, 1100000, 1080000, 1150000, 1200000],
'cost': [600000, 650000, 620000, 670000, 700000, 740000,
690000, 720000, 770000, 760000, 810000, 850000]
})
monthly_revenue.to_sql('monthly_revenue', conn, if_exists='replace', index=False)
print("月度收入成本数据已创建")
# ROW_NUMBER 和 RANK 示例:客户销售额排名
query = """
SELECT
customer_id,
customer_name,
SUM(amount) as total_sales,
ROW_NUMBER() OVER (ORDER BY SUM(amount) DESC) as row_num,
RANK() OVER (ORDER BY SUM(amount) DESC) as rank,
DENSE_RANK() OVER (ORDER BY SUM(amount) DESC) as dense_rank
FROM (
SELECT
c.customer_id,
c.customer_name,
r.amount
FROM customers c
JOIN receivables r ON c.customer_id = r.customer_id
)
GROUP BY customer_id, customer_name
ORDER BY total_sales DESC
"""
result = pd.read_sql_query(query, conn)
print("\n窗口函数:客户销售额排名:")
print(result)
# LAG 和 LEAD 示例:环比分析
query = """
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) as prev_month_revenue,
LEAD(revenue) OVER (ORDER BY month) as next_month_revenue,
revenue - LAG(revenue) OVER (ORDER BY month) as mom_change,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month)) /
LAG(revenue) OVER (ORDER BY month), 2) as mom_growth_rate
FROM monthly_revenue
ORDER BY month
"""
result = pd.read_sql_query(query, conn)
print("\nLAG 和 LEAD 函数:月度环比分析:")
print(result)
# 累计求和:计算年度累计收入
query = """
SELECT
month,
revenue,
SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as ytd_revenue,
ROUND(100.0 * revenue / SUM(revenue) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 2) as pct_of_ytd
FROM monthly_revenue
ORDER BY month
"""
result = pd.read_sql_query(query, conn)
print("\n累计求和:年度累计收入(YTD):")
print(result)
# 分组窗口函数:按科目类型分析
query = """
SELECT
c.account_type,
c.account_code,
c.account_name,
SUM(j.debit) as total_debit,
SUM(j.credit) as total_credit,
AVG(SUM(j.debit + j.credit)) OVER (PARTITION BY c.account_type) as type_avg_amount,
SUM(SUM(j.debit + j.credit)) OVER (PARTITION BY c.account_type) as type_total_amount
FROM chart_of_accounts c
JOIN journal_entries j ON c.account_code = j.account_code
GROUP BY c.account_type, c.account_code, c.account_name
ORDER BY c.account_type, total_debit + total_credit DESC
"""
result = pd.read_sql_query(query, conn)
print("\n分组窗口函数:按科目类型的交易分析:")
print(result)
# 移动平均:3个月移动平均
query = """
SELECT
month,
revenue,
ROUND(AVG(revenue) OVER (
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 2) as ma_3month
FROM monthly_revenue
ORDER BY month
"""
result = pd.read_sql_query(query, conn)
print("\n移动平均:3个月收入移动平均:")
print(result)