create an interval variable based on a value column

时间:2018-06-04 17:39:07

标签: sql sql-server intervals

I work in MS SQL Server. I have a dataset of which a subset looks like below:

id;tax
cvw;8525
jhf;9958
dsf;10843
dsd;12001
xyz;12999
dgs;13586
das;14001
fsa;16428

Now, I want to replace (or create a new column, either way is fine) some values in the tax-column with its value but where every value above 9999 gets placed in an interval with increments of 1000. So that it would look like this:

id;tax;tax_replaced
cvw;8525;8525
jhf;9958;9958
dsf;10843;10000
dsd;12001;12000
xyz;12999;12000
dgs;13586;13000
das;14001;14000
fsa;16428;16000

I have tried to find an easy way to code this, but so far failed. I had a thought of creating the interval in a temp table with 2 columns and from there derive the column "tax_replaced" but I can´t find a way to do it. Any suggestions are most welcome!

Best regards, /T.

3 个答案:

答案 0 :(得分:0)

You seems to want case expression here :

select *, (case when tax > 9999 
                then floor(tax / 1000) * 1000
                else tax
            end) as tax_replaced
from table t;

You can also use % operator :

select *, (case when tax > 9999 
                then tax - (tax % 10000)
                else tax
           end) as tax_replaced
from table t;

答案 1 :(得分:0)

Leave the tax as it is, if it's less than or equal 10000, otherwise replace it by floor(tax / 1000) * 1000.

UPDATE elbat
       SET tax = floor(tax / 1000) * 1000
       WHERE tax > 10000;

答案 2 :(得分:-1)

The easiest way would probably be to do your value minus the modulo return.

DECLARE @val INT = 16428

select @val - (@val%1000)

To put it in your code:

SELECT *, 
CASE WHEN tax >= 10000 THEN tax - (tax%1000) ELSE tax END AS tax_replaced