给出一个包含每月交易量(客户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)根据上表,每月有多少人(每月,从一个计划到另一个计划,#个客户)切换计划?
答案 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