Presto SQL计算两列价格百分比结果错误,求修正方案
问题分析与解决方案
错误原因
- 整数除法导致计算偏差:当
first_price和last_price为整数类型时,Presto会执行整数除法,比如10/11结果为0,66/68结果也为0,最终1 - 0 = 1,这就是你得到1.0错误结果的核心原因。 - 多余的
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
结果验证
执行上述查询后,对应数据的计算结果会符合预期:
| ID | first_price | last_price | first_vs_last_percentages |
|---|---|---|---|
| 1 | 10 | 11 | 0.090909... |
| 2 | 66 | 68 | 0.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
相关产品推荐
相关产品推荐

