【问题标题】:How can I grab top selling product for each month using sql?如何使用 sql 获取每个月最畅销的产品?
【发布时间】:2020-01-28 17:19:28
【问题描述】:

给定一个包含每月交易(客户 ID、月份、付款)的表格和一个包含客户信息(类型 2 维度)(id、cust_id、计划类型、用户数量、开始日期、结束日期)的表格:

每月收入最高的计划是什么(月、美元、计划)?

我在下面的回答似乎只会按数量而不是按月返回顶级产品计划。

SELECT 
    Sales.month as SalesMonth, 
    SUM(Sales.payment) AS MonthlySales, 
    CustomerInfo.plan_type AS PlanType 
FROM Sales 
INNER JOIN CustomerInfo ON Sales.customer_id=CustomerInfo.cust_id
GROUP BY SalesMonth, MonthlySaleS, PlanType 
ORDER BY MonthlySales, PlanType
ORDER BY MonthlySales DESC 
LIMIT 1

我被接下来的两个难住了。

2) 鉴于上表,每个月带来多少客户(月、计划、# 个新客户)?

3) 鉴于上述表格,每月有多少人转换计划(每月,从计划到计划,# 个客户)?

【问题讨论】:

    标签: sql inner-join aggregate-functions greatest-n-per-group


    【解决方案1】:

    您可以按照以下方式进行:

    • 首先使用聚合查询来计算每个计划的月销售额
    • 然后按月分区内的月销售额降序排列记录
    • 最后,过滤每个月的最高记录

    查询:

    SELECT SalesMonth, PlanType, MonthlySales
    FROM (
        SELECT 
            x.*, 
            ROW_NUMBER() OVER(PARTITION BY as SalesMonth ORDER BY MonthlySales desc) rn
        FROM (
            SELECT 
                s.month as SalesMonth, 
                c.plan_type AS PlanType, 
                SUM(s.payment) AS MonthlySales
            FROM sales s
            INNER JOIN CustomerInfo s ON s.customer_id = c.cust_id
            GROUP BY s.month, c.plan_type
        ) x
    ) y
    WHERE rn = 1
    

    【讨论】:

    • y 在做什么?您如何过滤每个月的最高记录?感谢您的帮助!
    • @DrewPham:y 是子查询生成的派生表的别名。结局 WHERE 子句登上了每个月的最高记录。
    • Sorry new to stack overflow 我如何才能知道每个月(月、计划、# 个新)带来了多少新客户?
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多