Question

How to set the decimal values to a condition based value for underlying number using case when in T-Sql? Example to clarify:

Column SalesPrice is used for prices (2 decimals), like 129.99 or 19.99 for example.

I would like to select SalesPrice, but with a slight adjustment in the result:

  • If SalesPrice >= 100 the decimals should be .00 (129.99 --> 130.00)
  • If SalesPrice < 100 the decimals should be .95 ( 19.99 --> 19.95)

Thanks!

Was it helpful?

Solution

Assuming all values are positive, here is one approach:

update t
    set SalesPrice = (case when SalesPrice >= 100 then floor(SalesPrice) + 1
                           when SalesPrice < 100 then floor(SalesPrice) + 0.95
                      end)
    where (SalesPrice - floor(SalesPrice)) >= 0.9;

I added the where clause so this only affects prices where the decimal amount is greater than 0.90. That way, prices like 15.49 are not affected. You can adjust this to your needs. If you wanted to affect all prices with decimal values, then:

update t
    set SalesPrice = (case when SalesPrice >= 100 then floor(SalesPrice) + 1
                           when SalesPrice < 100 then floor(SalesPrice) + 0.95
                      end)
    where SalesPrice > floor(SalesPrice);

The where clause guarantees that there is a decimal amount. This prevents 21 from turning into 21.95 for instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top