You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SQL计算用户近30天消费金额并生成含TOP商品的聚合表?

需求与SQL实现

现有数据表

transaction_details表(交易明细)

transaction_idcustomer_iditem_iditem_numbertransaction_dttm
776512312022-01-15
125421242022-02-03
333235622022-02-15
765814312022-03-01
723145612022-01-15
723122322022-01-29

dict_item_prices表(商品价格字典)

item_iditem_nameitem_pricevalid_from_dtvalid_to_dt
23phone 110002022-01-012022-12-31
12notebook50002022-01-022022-12-31
56cup502022-01-022022-12-31
43glasses7002022-01-012022-12-31

目标统计表格(customer_aggr)

customer_idamount_spent_lmtop_item_lm
1700glasses
220000notebook
3100cup

计算规则

  • 关联dict_item_prices表,采用交易发生时有效的商品单价进行计算;
  • 仅统计报告生成时间前30天内有消费记录的用户;
  • 最终表需包含用户ID、近30天消费总金额、该用户此期间消费金额最高的商品名称。

SQL实现语句

WITH transaction_with_price AS (
    SELECT
        td.customer_id,
        td.item_id,
        dip.item_name,
        td.item_number * dip.item_price AS item_total,
        td.transaction_dttm
    FROM transaction_details td
    JOIN dict_item_prices dip 
        ON td.item_id = dip.item_id
        AND td.transaction_dttm BETWEEN dip.valid_from_dt AND dip.valid_to_dt
    WHERE td.transaction_dttm >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
),
customer_item_summary AS (
    SELECT
        customer_id,
        item_name,
        SUM(item_total) AS item_total_amount,
        SUM(SUM(item_total)) OVER (PARTITION BY customer_id) AS amount_spent_lm,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id 
            ORDER BY SUM(item_total) DESC, item_name ASC
        ) AS item_rank
    FROM transaction_with_price
    GROUP BY customer_id, item_name
)
SELECT
    customer_id,
    amount_spent_lm,
    item_name AS top_item_lm
FROM customer_item_summary
WHERE item_rank = 1
ORDER BY customer_id;

内容的提问来源于stack exchange,提问作者useless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:35:17