calculate a derived column in sql

61 Views Asked by At

I have a following query which produces table below:-

select * from temp_3

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

Now I need the values to be in percentage of the total sum of values for which I wrote following query :-

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

But that led to following result :-

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

can anyone give me an idea as to how we can convert that efficiently into percentage form ? and where I am going wrong ?

2

There are 2 best solutions below

0
On

Use window functions:

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

or just

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