0

我想按月计算打开和交付项目之间的百分比。我有下表:

     date       | delivered | opened
  01/04/2021           1        1
  01/04/2021           1
  01/04/2021           1
  08/05/2021           1        1
  08/05/2021           1        1
  10/03/2021           1
  10/03/2021           1        1

然后将像这样添加百分比:

 date_month | delivered | opened | percentage_opened
  4             1          1            0.33
  4             1                       0.33
  4             1                       0.33
  5             1          1            1
  5             1          1            1
  3             1                       0.5
  3             1          1            0.5

我尝试了以下方法,但收到错误消息“内部错误:系统尝试为虚拟表运行表创建”。

select
    opened, 
    delivered,
    month(date) as date_month,
    sum(opened)/sum(delivered) over(partition by month(date)) as percentage_opened
from table
;
4

1 回答 1

0

你很接近,但你需要两个分析函数。您还应该包括年份:

select opened,  delivered, month(date) as date_month,
       (sum(opened) over (partition by year(date), month(date)) * 1.0 /
        sum(delivered) over(partition by year(date), month(date))
       ) as ratio_opened
from table;

有些数据库会进行整数除法,所以我加入* 1.0以防万一。

于 2021-05-12T10:53:17.593 回答