qi1128 2022-01-18 15:04 采纳率: 100%
浏览 43
已结题

像计算累加占比前80%的产品 应该怎么添加语句

img

img

img

表结构如上:

我写的代码如下:
select (@num:=@num+1) '排名',t1.产品 as 产品名称,t1.销售金额 as 销售金额, (t1.销售金额/t2.总和) as 占比
from (select @num:=0) num,
(select cp.pname 产品,sum(priceSALE_AMOUNT) as 销售金额,1 as 关联
from 销量明细 xl
left join 客户明细 kh on xl.customId = kh.customId
left join 产品明细 cp on xl.pid = cp.pid
group by cp.pid
)t1
left join
(select sum(price
SALE_AMOUNT) as 总和,1 as 关联
from 销量明细 xl
left join 客户明细 kh on xl.customId = kh.customId

数据库是MySQL的
left join 产品明细 cp on xl.pid = cp.pid)t2
on t1.关联 = t2.关联
order by (t1.销售金额/t2.总和) desc

相求累计占比前80%的产品 该怎么添加语句呢

  • 写回答

1条回答 默认 最新

  • DarkAthena ORACLE应用及数据库设计方案咨询师 2022-01-18 16:38
    关注

    MYSQL8.0以上版本,使用开窗函数中的CUME_DIST,返回累计占比

    select * from (
    select cp.pid,
    cume_dist() over( order by sum(cp.price*xl.sale_amount) desc)  累计占比
    from 产品明细 cp left join 销量明细 xl
    on  xl.pid=cp.pid
    group by cp.pid) 
    where 累计占比<=0.8
    

    而且你这题和上一题都犯了个毛病,明明查询结果中不需要客户信息,产品明细和销量明细也不需要通过客户信息关联,为什么非得把客户明细带上去啊


    为什么要加到你那个语句里去啊?你不是要查累计占比前80%的产品么,这个sql查出来就是了,如果你要同时显示单个占比,多查一个字段就好了

    select * from (
    select cp.pid,
    sum(cp.price*xl.sale_amount) 销售金额,
    sum(cp.price*xl.sale_amount) /(sum(sum(cp.price*xl.sale_amount)) over() ) 占比,
    cume_dist() over( order by sum(cp.price*xl.sale_amount) desc)  累计占比
    from 产品明细 cp left join 销量明细 xl
    on  xl.pid=cp.pid
    group by cp.pid) 
    where 累计占比<=0.8
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月27日
  • 已采纳回答 1月19日
  • 创建了问题 1月18日

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端