计算sql中的派生列

问题描述

我有以下查询生成下表:-

select * from temp_3

bucket  values
OTIF+2  319
OTIF    24987              
null    1347               
OTIF+>2 515
OTIF+1  552

现在我需要这些值占我编写以下查询的总和的百分比:-

select sum(values) as total into temp_1 from temp_3
select bucket,(values/(select total from temp_1)) as score from temp_3

但这导致了以下结果:-

bucket  values
OTIF+2  0
OTIF    0              
null    0               
OTIF+>2 0
OTIF+1  0

谁能告诉我我们如何有效地将其转换为百分比形式?我哪里出错了?

解决方法

使用窗口函数:

select bucket,value,value * 1.0 / sum(value) over ()
from t;
,
select sum(values) as total into temp_1 from temp_3
select bucket,(values * 100) /total as score from temp_3,temp_1

或者只是

select bucket,(values * 100) /sum(values) as score from temp_3