目前我得到的输出为“25/50”作为字符串通过SQL,现在我需要从此得分计算百分比,并使用SQL语句返回该值Post Gres SQL。我需要使用SQL语句计算得分百分比
SELECT es.score FROM emp_scores es WHERE id = 123;
这会返回一个字符串“25/50”。现在我想从这个字符串计算百分比。
目前我得到的输出为“25/50”作为字符串通过SQL,现在我需要从此得分计算百分比,并使用SQL语句返回该值Post Gres SQL。我需要使用SQL语句计算得分百分比
SELECT es.score FROM emp_scores es WHERE id = 123;
这会返回一个字符串“25/50”。现在我想从这个字符串计算百分比。
需要分割你的数据第一次,那么你可以计算出百分比... 可以使用
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;
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;
又如使用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;
它存储在da tabase为'25/50'? – Szymon
你可以使用子字符串在sql中进行转换,但这些操作通常更容易在更高级别上执行。 – adrianm
您不应将这些值保存在同一列中。如果每场比赛只有两支球队,将他们分成两列。或者创建一个与1:n连接的分数的新表格,以跟踪一个比赛中两个以上的球队及其得分。 – func0der