2014-03-28 66 views
0

目前我得到的輸出爲「25/50」作爲字符串通過SQL,現在我需要從此得分計算百分比,並使用SQL語句返回該值Post Gres SQL。我需要使用SQL語句計算得分百分比

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

這會返回一個字符串「25/50」。現在我想從這個字符串計算百分比。

+0

它存儲在da tabase爲'25/50'? – Szymon

+0

你可以使用子字符串在sql中進行轉換,但這些操作通常更容易在更高級別上執行。 – adrianm

+1

您不應將這些值保存在同一列中。如果每場比賽只有兩支球隊,將他們分成兩列。或者創建一個與1:n連接的分數的新表格,以跟蹤一個比賽中兩個以上的球隊及其得分。 – func0der

回答

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; 
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; 
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;