细分字符串并使用子字符串作为分数组件



我正试图从mySQL查询返回一组字符串值。然后在"/"字符处将它们分开(它们都包含)。最后将"/"字符之前的值除以后面的值

我已经尝试将SUBSTRING转换为INT和几个DECIMAL变体。感激地接受任何帮助。

        "
        CAST(
            CAST(
                SUBSTRING(
                    customerfeedback.total_score, 
                    0, LOCATE('/', table.column_a-1)
                )AS DECIMAL(6,3)
            )
            /
            CAST(
                SUBSTRING(
                    customerfeedback.total_score,
                    LOCATE('/', table.column_a+1), LENGTH(table.column_a)
                )AS DECIMAL(6,3)
            )
            AS DECIMAL(6,3)
        )
        "

使用substring_index提取分子和分母部分,并在除法中使用它们。

示例

select 
  @str:='225/12', 
  @n:=substring_index( @str, '/', 1 ) numerator, 
  @d:=substring_index( @str, '/', -1 ) denominator, 
  @n/@d quotient;

上述示例的结果

+----------------+-----------+-------------+----------+
| @str:='225/12' | numerator | denominator | quotient |
+----------------+-----------+-------------+----------+
| 225/12         | 225       | 12          |    18.75 |
+----------------+-----------+-------------+----------+

您可以根据需要对商进行强制转换或舍入。

最新更新