用开窗函数代替子查询优化以下mysql代码:select item_category,sum(amount) as 销售额, sum(sum(amount)) over (order by sum(amount) desc) as 累计销售额, sum(sum(amount)) over (order by sum(amount) desc)/ (select sum(amount) from userbehavior_new where behavior_type='buy') as 累计销售额占比 from userbehavior_new group by item_category order by 销售额 desc;
时间: 2024-04-09 21:28:24 浏览: 61
mysql关联子查询的一种优化方法分析
使用开窗函数代替子查询优化后的MySQL代码如下:
```sql
SELECT item_category,
SUM(amount) AS 销售额,
SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC) AS 累计销售额,
SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC) / buy_sum AS 累计销售额占比
FROM userbehavior_new
CROSS JOIN (
SELECT SUM(amount) AS buy_sum
FROM userbehavior_new
WHERE behavior_type = 'buy'
) AS T
GROUP BY item_category
ORDER BY 销售额 DESC;
```
优化点:
1. 使用开窗函数SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC)将累计销售额计算为一个窗口函数,以避免子查询。
2. 使用CROSS JOIN将子查询中的总购买金额与每个item_category的销售额进行关联。
3. 保持原有的GROUP BY和ORDER BY子句不变。
阅读全文