sql - 如何使用 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) 鉴于上表,每月有多少人转换计划(月,从计划到计划,# 个客户)?
解决方案
您可以进行如下操作:
- 首先使用聚合查询来计算每个计划的月销售额
- 然后按月分区内的月销售额降序排列记录
- 最后,过滤每个月的最高记录
询问:
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
推荐阅读
- pandas - 使用 groupby() 从后面进行累积乘法
- python - 为什么以不同的方式生成数组会导致代码不同部分的大量加速?
- javascript - ES8 和 ES9 中的 jshint 指的是什么?
- r - 错误 1:从 JavaScript 动态生成 Web 抓取时下标越界
- openssl - 在 OpenSSL 命令行工具中为自定义扩展创建自己的 ASN.1 模块
- jquery - 将导航栏品牌和链接与 Bootstrap 4 中的页面内容对齐
- node.js - 如何通过 nodejs express 应用程序调用 API 获取 png 图像
- javascript - Android 版 Chrome 中文本输入的奇怪行为
- java - 如果我在嵌入式 tomcat 上运行我的 Rest API 并且 IDE 已关闭,它从哪里运行?
- laravel - Laravel-echo-server 码头化问题