如何在 window 函数和 Case when 语句中使用除法

How to use division with window function and Case when statement

它适用于 sum() 但不适用于 sum()/sum()

使用 sum():

select *, 
case when time_of_day_viewers_time_zone >= '06:00:00 -
06:59:59' and time_of_day_viewers_time_zone <= '10:00:00 - 10:59:59'
then sum(amount_spent_usd) over () else null end as cpm 
from t1

不适用于 sum()/sum():

select *,
case when time_of_day_viewers_time_zone >= '06:00:00 - 06:59:59'
and time_of_day_viewers_time_zone <= '10:00:00 - 10:59:59'
then sum(amount_spent_usd)/sum(impressions)*1000 
over () else null end as cpm
from t1

edit1:即使我使用 sum(amount_spent_usd)/nullif(sum(impressions),0)*1000 它仍然说 'syntax error at or near "over" '

编辑2:

sum(amount_spent_usd) over () / (sum(impressions) over () * 1000)

如果我使用这个查询,它会计算所有 24 小时的总和,这意味着不应用 when 语句的情况。如何解决这个问题?

编辑4: 终于我使用了这个查询,虽然它很长..

 (sum(case when time_of_day_viewers_time_zone >= '06:00:00 - 06:59:59'
and time_of_day_viewers_time_zone <= '10:00:00 - 10:59:59'
then amount_spent_usd else null end) over () /sum(case when time_of_day_viewers_time_zone >= '06:00:00 - 06:59:59'
and time_of_day_viewers_time_zone <= '10:00:00 - 10:59:59'
then impressions else null end) over ())*1000 as new

提前致谢

您不能对两个 window 函数使用 over(),您需要分别为每个函数提供 windowing 子句。乘法需要对整个表达式进行:

sum(amount_spent_usd) over () / (sum(impressions) over () * 1000)