SQL 计算两列之间的百分比

SQL calculate percentage between two columns

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

     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

我尝试了以下方法,但在读取 'Internal error: system tried to run table creation for virtual table' 时出现错误。

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

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

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 以防万一。