Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1569944
  • 博文数量: 201
  • 博客积分: 2812
  • 博客等级: 少校
  • 技术积分: 3029
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-18 18:28
个人简介

从事数据库工作多年,目前看好分布式NeSQL/HTAP数据库在企业客户市场的发展。未来的主要方向是——致力于 NewSQL/HTAP 数据库的推广普及。

文章存档

2016年(1)

2015年(8)

2014年(23)

2013年(50)

2012年(32)

2011年(87)

分类: Sybase

2012-07-24 10:28:09

   近日遇到一个问题:“表中有两个字段,类型为numeric(18,4)。这两个字段相除,需要四舍五入到小数点后3位”。 使用类似于 SELECT convert(numric(18,2),colA/colB) FROM tablename的方式时,IQ直接进行截断,并没有四舍五入。
  
   下面以一个例子说明问题如何解决:
 
   1. 首先创建测试用表 test1,并插入测试数据
      create table test1(id int, col1 money, col2 money);
      insert into test1 values(1,1234.2789,2345.2216);
      commit;
 
   2. 执行如下查询:
      select col1/col2 from test1;   --输出结果: 0.52629521235861037609
   
      select cast(col1/col2 as numeric(2,2)) from test1  --输出结果:0.52   
 
      我们看到,使用cast函数输出结果是0.52 被截断了,我们希望小数点后第3为能四舍五入,希望结果为0.53 .
 
    3. 使用round函数可以实现四舍五入功能:

       select cast(round(col1/col2,2) as numeric(3,2)) from test1  --输出:0.53 ,希望的结果
       或者使用convert函数
       select convert(numeric(3,2),round(col1/col2,2)) from test1  --输出:0.53 ,希望的结果
阅读(3771) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

Leichunyi10072014-04-20 15:49:00

向您请教下numeric  什么时候是四舍五入

Leichunyi10072014-04-20 15:48:01

create table test1(id int, col1 money, col2 money);
      insert into test1 values(1,1234.2789,2345.2216);


 select col1/col2 from test1;   --输出结果: 0.52629521235861037609
   
      select cas(col1/col2 as numeric(2,2)) from test1  --输出结果:0.52    


我刚执行了一遍结果是: 0.53 不是 0.52