【问题标题】:Calculate the percentage using Over Partition By使用 Over Partition By 计算百分比
【发布时间】:2021-12-01 21:29:49
【问题描述】:

我想添加一个计算列,以百分比为每个商店计算“苹果”的唯一订单号。例如,A 店一共有 4 个订单,但其中有 2 个订单号相同。因此,store a 的“苹果”订单百分比为 2/3 = 67%

   store       order no    product      
     a           abc         apple        
     a           bde         orange
     a           abc         apple
     a           feg         apple
     b           lmn         apple         
     b           mno         pear
     c           tsx         apple         

愿望输出应该是这样的:

   store       product     
     c          100%  
     a          67%   
     b          50%       

这是我尝试过的查询:

count(distinct(case when product = 'apple' then order no end) 
 /
count(distinct order no) over(partition by store)

由于某种原因,上面的查询没有返回每个商店的正确百分比。 任何建议将不胜感激。

【问题讨论】:

    标签: mysql sql window-functions


    【解决方案1】:
    SELECT store,
           SUM(product = 'apple') / COUNT(*) 
    FROM ( SELECT DISTINCT *
           FROM table ) t
    GROUP BY 1
    ORDER BY 2 DESC
    

    不需要窗口函数。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 2021-12-27
      • 2021-12-30
      • 2017-11-02
      • 2013-05-31
      • 2016-07-02
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多