目前我得分为" 25/50"作为字符串通过SQL,现在我需要从这个分数计算百分比并使用Post Gres SQL中的SQL语句返回该值。
SELECT es.score FROM emp_scores es WHERE id = 123;
这会给我一个字符串" 25/50"。现在我想从这个字符串中计算出百分比。
答案 0 :(得分:0)
您需要首先拆分数据,然后才能计算百分比...... 你可以用
split_part(string text, delimiter text, field int)
//Split string on delimiter and return the given field (counting from one)
这是示例
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;
答案 1 :(得分:0)
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;
答案 2 :(得分:0)
使用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;