从SQL计算Floor()时出错

时间:2011-09-06 06:05:19

标签: sql floor

我需要计算工资准备所需的钞票数量。 我对最后一栏有问题,即USD1。

我将获得USD1 = 2的值。

DECLARE @GrossPay Decimal(12,2)
SET @GrossPay = 132.78

SELECT
    @GrossPay,
    FLOOR(@GrossPay/100) AS USD100,
    FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50) AS USD50,
    FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20) AS USD20,
    FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20)/10) AS USD10,
FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20)/10))*10)/5) AS USD5,
FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20 -(FLOOR((@GrossPay -
FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20)/10))*10-(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay -
FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50 - (FLOOR((@GrossPay -
FLOOR(@GrossPay/100)*100 -(FLOOR((@GrossPay - FLOOR(@GrossPay/100)*100)/50))*50)/20))*20)/10))*10)/5))*5)/1) AS USD1

很抱歉这么久的查询。

您可以复制并粘贴上面的Sql Query并执行它,然后您将了解我的意思。希望任何人都可以帮助我。

提前致谢!

2 个答案:

答案 0 :(得分:0)

考虑使用ROUND

SELECT ROUND(2.78,0)

或者,添加0.5会使floor向上舍入而不是下限:

SELECT FLOOR(2.78+0.5)

答案 1 :(得分:0)

如果你意识到你不需要减去计算出的先前数量,那么很多你的表达式都可以被简化(目前唯一一个我不能得到合适的表达式的是USD10)。例如,USD1列始终是0到4之间的值,基于将整个金额除以5的余数。

这是模运算符的定义,在SQL中这是%,所以我们可以:

(CONVERT(int,@GrossPay)%5) as USD1

正如我所说,大多数其他人也可以使用模数计算(除了USD10,仍然试图考虑简化)。我还介绍了另一个名为@GrossPayInt的变量,因为它会自动处理舍入:

DECLARE @GrossPay Decimal(12,2) SET @GrossPay = 132.78
DECLARE @GrossPayInt int SET @GrossPayInt = @GrossPay

SELECT @GrossPay,
    @GrossPayInt/100 as USD100,
    (@GrossPayInt%100)/50 as USD50,
    (@GrossPayInt%50)/20 as USD20,
    CASE WHEN (@GrossPayInt%100)/10 IN (1,3,6,8) THEN 1 ELSE 0 END as USD10 as USD10,
    (@GrossPayInt%10)/5 as USD5,
    (@GrossPayInt%5) as USD1

如果其他人可以为10美元建议一个好的短语,我认为这已经完成了。