首页 > 解决方案 > 如何使用 sql 获取每个月最畅销的产品?

问题描述

给定一个包含每月交易(客户 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) 鉴于上表,每月有多少人转换计划(月,从计划到计划,# 个客户)?

标签: sqlinner-joinaggregate-functionsgreatest-n-per-group

解决方案


您可以进行如下操作:

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

询问:

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

推荐阅读