优化以下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 18:28:24 浏览: 75
优化后的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) / total_buy_sum AS 累计销售额占比
FROM userbehavior_new
CROSS JOIN (
SELECT SUM(amount) AS total_buy_sum
FROM userbehavior_new
WHERE behavior_type = 'buy'
) AS T
GROUP BY item_category
ORDER BY 销售额 DESC;
```
优化点:
1. 使用子查询获取总购买金额,使得计算累计销售额占比的部分只需执行一次。
2. 使用CROSS JOIN将总购买金额与每个item_category的销售额进行关联。
3. 使用SUM(amount)计算销售额,SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC)计算累计销售额,SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC) / total_buy_sum计算累计销售额占比。
4. 对销售额进行降序排序,以便按照降序排列结果。
相关问题
优化以下mysql代码:select item_category,sum(amount) as 销售额, sum(sum(amount)) over (order by sum(amount) desc) as 累计销售额 from userbehavior_new group by item_category order by 销售额 desc;
优化后的MySQL代码如下:
```sql
SELECT item_category,
SUM(amount) AS 销售额,
SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC) AS 累计销售额
FROM userbehavior_new
GROUP BY item_category
ORDER BY 销售额 DESC;
```
优化点:
1. 使用SUM(SUM(amount)) OVER (ORDER BY SUM(amount) DESC)将累计销售额计算为一个窗口函数,以避免子查询。
2. 保持原有的GROUP BY和ORDER BY子句不变。
用开窗函数代替子查询优化以下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;
使用开窗函数代替子查询优化后的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子句不变。
阅读全文