【问题标题】:I need to calculate percentage from score using a SQL statement我需要使用 SQL 语句从分数中计算百分比
【发布时间】:2014-05-07 19:00:02
【问题描述】:

目前,我通过 SQL 将分数输出为“25 / 50”作为字符串,现在我需要根据该分数计算百分比并使用 Post Gres SQL 中的 SQL 语句返回该值。

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

这会返回一个字符串为“25 / 50”。现在我想计算这个字符串的百分比。

【问题讨论】:

  • 在数据库中是否存储为25 / 50
  • 您可以在 sql 中使用子字符串进行转换并进行转换,但此类操作通常在更高级别上更容易进行。
  • 您不应将这些值保存在同一列中。如果每场比赛只有两支球队,则将它们分成两列。或者为与其具有 1:n 联系的比分创建一个新表,以跟踪多于两支球队及其一场比赛的比分。

标签: sql postgresql percentage


【解决方案1】:

您需要先拆分数据,然后才能计算百分比... 你可以使用

    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;

【讨论】:

    【解决方案2】:
    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;
    

    【讨论】:

      【解决方案3】:

      另一个使用 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;
      

      【讨论】:

        猜你喜欢
        • 2010-10-20
        • 2020-10-17
        • 1970-01-01
        • 2014-06-24
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多