Question

Currently I am getting output for score as " 25 / 50 " as string through SQL, now I need to calculate percentage from this score and return that value using a SQL statement in Post Gres SQL.

SELECT es.score FROM emp_scores es WHERE id = 123;

This returns me a string as " 25 / 50 ". Now I want to calculate the percentage from this string.

Was it helpful?

Solution

you need to split your data first then you can calculate percentage... you can use

    split_part(string text, delimiter text, field int)  
   //Split string on delimiter and return the given field (counting from one)   

here is example

SELECT (CAST(coalesce(split_part(es.score,'/',2)*100), '0') AS integer)*100)/CAST(coalesce(split_part(es.score,'/',1)*100), '0') AS integer) as 'Percentage' FROM emp_scores es WHERE id = 123;

OTHER TIPS

select 
cast(substring(es.score,0,patindex('%/%',es.score)) as int)/
cast(substring(es.score
       ,patindex('%/%',es.score)+1
       ,len(es.score)-patindex('%/%',es.score)) as int)*100
FROM emp_scores es WHERE id = 123;

Another example using cte

create table emp_scores (
   gid serial primary key,
   score varchar
);
insert into emp_scores values (123,  ' 25 / 50 ');

with t as (
    select regexp_split_to_array(' 25 / 50 ', '/') scores from emp_scores where gid = 123
)
select 100 * scores[1]::real / scores[2]::real from t;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top