如何限制AVG或SUM计算的值

问题描述

我想使AMY的结果值在300以内。

example
270 -> 270
300 -> 300
350 -> 300 

我应该如何修改它? 可以在有情况的情况下使用用例吗?

select 
no,sum(case when type = 'A' then cost else -cost end) * 0.08 as AMY 
from MIKE
where 
MIKE.type in ('A','B') 
and exists (select 1 from users u where u.no = c.otaku_no)
group by no

解决方法

您可以使用least()

   least(sum(case when type = 'A' then cost else -cost end) * 0.08,300) as AMY 

如果sum()超过300,则返回值为300。如果要施加最小值,可以使用greatest()。因此,这将确保该值在-300到300之间:

   greatest(least(sum(case when type = 'A' then cost else -cost end) * 0.08,300),-300) as AMY