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

如何在PostgreSQL中通过两列运算生成第三列百分比结果

PostgreSQL 实现每行占比计算与结果拼接

解决方案SQL

SELECT 
    Name,
    Apple,
    Orange,
    CONCAT(
        ROUND((Apple::numeric / (Apple + Orange)) * 100, 2) || '% Apple, ',
        ROUND((Orange::numeric / (Apple + Orange)) * 100, 2) || '% Orange'
    ) AS Result
FROM Persons;

关键细节说明

  • 避免整数除法误差:将Apple和Orange转为numeric类型,防止PostgreSQL中整数除法直接取整的问题(例如2/3若用整数运算会得到0,转为numeric后能保留小数精度)。
  • 百分比格式化:通过ROUND(..., 2)保留两位小数,确保结果与预期的百分比格式完全匹配。
  • 字符串拼接:使用||操作符和CONCAT函数,将计算后的百分比值与描述文本组合成Result列的最终内容。

执行结果验证

运行上述SQL后,将得到符合需求的输出:

NameAppleOrangeResult
A2166.67% Apple, 33.33% Orange
A3175.00% Apple, 25.00% Orange
A1150.00% Apple, 50.00% Orange
B2433.33% Apple, 66.67% Orange
B3260.00% Apple, 40.00% Orange

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:50:43