Skip to content
Advertisement

How to short a sql case query that uses between

Hi have this sql query:

SELECT CASE
   WHEN money BETWEEN 0 and 1000 THEN '1000'
   WHEN money BETWEEN 1000 and 2000 THEN '2000'
   WHEN money BETWEEN 2000 and 3000 THEN '3000'
   .
   .
   .
   .
   .
   WHEN money BETWEEN 19000 and 20000 THEN '20000'

from bank;

How can I short this query so I don’t use a lot of case statements?

Advertisement

Answer

You can try using mod subtracting the remainder t from you value by division for 1000

SELECT money - MOD( money , 1000 )
FROM bank;

or as suggested by @DM you can also use

FLOOR((money + 999) / 1000) * 1000

the difference should be the same .. both involve function .. but there are nit where condition so this is not in contrast with indexing

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement