简体   繁体   中英

db2: how to remove the decimal from number column?

A very simple query which work

select avg(price) from cars where type = 'electric';

the result is

1                                
---------------------------------
                45000,00000000000

I want to remove the ,00000000000 to obtain

   1                                
    ---------------------------------
                    45000

I have tried cast and round but without success. I'm on Db2

This nice ltrim works fine for all type of cars

select replace(ltrim(replace(price,'0',' ')),' ','0') from cars;

but using with avg return the string with the 00000

select replace(ltrim(replace(avg(price),'0',' ')),' ','0') from cars where type = 'electric';

the result is..

45000.00000000000

:( Only the , is changed.

cast ing this value should just work:

select cast(avg(price) as int) as avg_int
from cars 
where type = 'electric';

Casting as an integer as suggested by another answer will work.

However, keep in mind that

  1. you'll be truncating any decimal values.
  2. you're converting from one type to another.

You can resolve #1 by casting after ROUND()

select int(round(avg(price),0)) as avg_int
from cars 
where type = 'electric'

You can resolve #2 by using DECIMAL() or ZONED() with zero for scale depending on the original column type.

select dec(avg(price),10,0) as avg_dec
from cars 
where type = 'electric'

And of course ROUND() could be used with DECIMAL() or ZONED() also...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM