如何使用sql来获取每月销量最高的产品?

时间:2019-09-28 21:37:46

标签: 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)根据上表,每月有多少人(每月,从一个计划到另一个计划,#个客户)切换计划?

1 个答案:

答案 0 :(得分: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
相关问题