You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中能否直接获取两个数值的最简比例?

获取两列的最简整数比例

要得到num_of_shares和num_of_shares_new的最简整数比,核心是先计算两个数的最大公约数(GCD),再用两数分别除以这个公约数,最后拼接成a:b的格式。不同SQL数据库的内置GCD函数实现略有不同,以下是主流数据库的直接实现方案:

MySQL/MariaDB

直接使用内置的GCD()函数:

SELECT 
  CONCAT(
    num_of_shares / GCD(num_of_shares, num_of_shares_new),
    ':',
    num_of_shares_new / GCD(num_of_shares, num_of_shares_new)
  ) AS simplified_ratio
FROM your_table;

针对你的示例数据(10和12),GCD(10,12)返回2,计算后得到5:6。

PostgreSQL 16+

PostgreSQL 16及以上版本内置了gcd()函数,用法和MySQL一致:

SELECT 
  CONCAT(
    num_of_shares / gcd(num_of_shares, num_of_shares_new),
    ':',
    num_of_shares_new / gcd(num_of_shares, num_of_shares_new)
  ) AS simplified_ratio
FROM your_table;

SQL Server 2022+

SQL Server 2022开始支持GCD()函数,实现方式相同:

SELECT 
  CONCAT(
    num_of_shares / GCD(num_of_shares, num_of_shares_new),
    ':',
    num_of_shares_new / GCD(num_of_shares, num_of_shares_new)
  ) AS simplified_ratio
FROM your_table;

注意事项

  • 确保num_of_shares和num_of_shares_new是整数类型,如果是小数,需要先通过CAST或ROUND转换为整数再计算。
  • 如果使用的数据库版本没有内置GCD函数,可能需要自定义函数,但这已属于你提到的“复杂函数”范畴,优先建议升级到支持内置GCD的版本。

内容的提问来源于stack exchange,提问作者ahrooran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:32:13