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

Presto SQL计算两列价格百分比结果错误,求修正方案

问题分析与解决方案

错误原因

  1. 整数除法导致计算偏差:当first_price和last_price为整数类型时,Presto会执行整数除法,比如10/11结果为0,66/68结果也为0,最终1 - 0 = 1,这就是你得到1.0错误结果的核心原因。
  2. 多余的sum()聚合:你已经按first_price和last_price分组,每组内这两个值是固定的,不需要用sum()进行聚合计算,这会进一步固化错误结果。

正确的Presto SQL查询

select 
    first_price, 
    last_price, 
    cast(1 - (first_price / cast(last_price as double)) as double) as first_vs_last_percentages 
from prices 
group by first_price, last_price 
having first_vs_last_percentages >= 0.1

或者更简洁的写法(通过1.0字面量触发浮点除法):

select 
    first_price, 
    last_price, 
    1 - (first_price / (last_price * 1.0)) as first_vs_last_percentages 
from prices 
group by first_price, last_price 
having first_vs_last_percentages >= 0.1

结果验证

执行上述查询后,对应数据的计算结果会符合预期:

IDfirst_pricelast_pricefirst_vs_last_percentages
110110.090909...
266680.029411...

补充说明

如果prices表中存在多条相同first_price和last_price的记录,且需要对这些记录的百分比差异做聚合(比如求平均值),可以调整为:

select 
    first_price, 
    last_price, 
    avg(1 - (first_price / cast(last_price as double))) as avg_first_vs_last_percentages 
from prices 
group by first_price, last_price 
having avg_first_vs_last_percentages >= 0.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:45:45