【问题标题】:Calculate the ratio dynamically using Partition By使用 Partition By 动态计算比率
【发布时间】:2021-12-27 07:32:05
【问题描述】:

我有一个数据集如下:

date        store    employee     products     sales        
20210101       a        ben          5         laptop        
20210101       a        ben         10         monitor       
20210201       b        tim         15         laptop        
20210301       b        tim         10         tablet         
20210301       a        ann         30         monitor        

我想做的是计算员工每分钟销售多少产品的比率。每个工作日每位员工有 6 小时轮班。例如:ben 在 2021 年 1 月 1 日的比率为 (5+10)/(6*60) = 0.04

我想创建一个动态计算,因此如果我们选择store a,它会显示所有员工及其班次的已售产品比率。例如:商店a总共有一个比率:(5+10+30) / (6*60*2) = 0.06

如果我们选择笔记本电脑,它的比例应该是:(5+10+30) / (6*60*2) = 0.06

这是我尝试过的查询:

(SUM('products') OVER (PARTITION BY 'date', 'store', 'employee', 'sales')) / (6*60) 

但是,这种计算不是动态的,我认为我遗漏了一些东西。如果有人能给我建议,我将不胜感激。

【问题讨论】:

  • 我有一个如下的数据集 最好以 CREATE TABLE + INSERT INTO 的形式提供。 我想为显示的示例数据提供所需的输出。

标签: mysql sql window-functions


【解决方案1】:

一个简单的 group by with rollup 应该可以解决问题。您将能够查看不同粒度级别的 sales_per_minute(例如商店、商店+员工或商店+员工+产品)。

with dummy_data as (
  select '20210101' as date_, 'a' as store, 'ben' as employee, 5 as products, 'laptop' as sales
  union all
  select '20210101', 'a', 'ben', 10, 'monitor'
  union all
  select '20210201', 'a', 'tm', 15, 'laptop'
  union all
  select '20210301', 'a', 'tim', 10, 'tablet'
  union all
  select '20210301', 'a', 'ann', 30, 'monitor'
)
select
  date_,
  store, 
  employee,
  sales,
  ROUND(SUM(products)/(6*60), 2) as sales_per_minute
from
  dummy_data
group by
  date_, store, employee, sales with rollup
order by
  1

输出

date_ store employee sales sales_per_minute
null null null null 0.19
20210101 null null null 0.04
20210101 a null null 0.04
20210101 a ben null 0.04
20210101 a ben laptop 0.01
20210101 a ben monitor 0.03

【讨论】:

    【解决方案2】:

    你想要的只是SUM(products) / 360。现在编写查询以获得总体比率或每个员工的比率或每个销售额的比率等。这些只是不同的组:

    select sum(products) / 360 as per_minute from mytable;
    
    select store, sum(products) / 360 as per_minute from mytable group by store;
    
    select employee, sum(products) / 360 as per_minute from mytable group by employee;
    
    select sales, sum(products) / 360 as per_minute from mytable group by sales;
    

    您当然也可以添加WHERE 子句来限制这一点,例如where date = '20210101'。 (顺便说一句,您真的将日期存储为字符串吗?或者这是您的示例数据中的显示内容?如果它应该是日期,请使用日期文字:where date = date '2021-01-01'。)

    当然你也可以创建复合组,例如

    select date, employee, sum(products) / 360 as per_minute
    from mytable
    group by date, employee
    order by date, employee;
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 2017-11-02
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多