关于SQL avg 小数点位数的截取
在取一个平均值的时候往往遇到小数点位数的截取。
前几天遇到过这么个问题,在KingDee EAS 的查询分析器里面如果求某一物料的平均单价时我这样写道:
select avg = case sum(bentry.FQuantity) when 0 then 0 else (sum(bentry.famount)/sum(bentry.FQuantity)) end,
此语句看似没什么问题,毕竟是求平均值,可是如果要在页面显示小数点后两位时要怎么做呢?此报表不是BI样式,就在sql中如何实现?
正常情况下可以考虑的解决方案由很多,如:
cast( Round(A.iPrice,2) as varchar(50)) AS 单价
cast( Round(A.iPrice,0,1) as varchar(50)) AS 单价
cast(0.329999999999999 as numeric(5,2)或者decimal)
但是很抱歉 KingDee EAS 6.0 里面我发现不能使用 cast ,round ,而cast *******
as numberic /decimal 就更不能用了。
还可以考虑substing()函数,concat()函数之类的。后来发现Oracle DB 里面有个关键性的函数:
charindex很管用于是写了段sql如下:
avg = case charindex('.',"tableName.avgprice ) when 0 then tableName.avgprice else substring(tableName.avgprice,0,charindex('.',tableName.avgprice)+2) end
如果平均值为整数而没有'.'存在时也能很好的解决。这就是搭配case 和charindex的作用于好处!
为了方便对这一SQL进行了整理。
/**
* 截取小数点后两位
* @author Kobe Bryant24
* @param strsql
* @param tableName
* @return
*/
protected String filtrateFloatValue(String strsql,String tableName){
return strsql+"=case charindex('.'," +
tableName+"."+strsql+") when 0 then " +
tableName+"."+strsql+" else substring(" +
tableName+"."+strsql+",0,charindex('.'," +
tableName+"."+strsql+")+2) end" ;
}
相关文档:
如果你经常遇到下面的问题,你就要考虑使用SQL Server的模板来写规范的SQL语句了:
SQL初学者。
经常忘记常用的DML或是DDL SQL 语句。
在多人开发维护的SQL中,每个人都有自己的SQL习惯,没有一套统一的规范。
在SQL Server Management Studio中,已经给大家提供了很多常用的现成SQL规范模板。
SQL Server Management ......
方法一:使用游标
declare @ProductName nvarchar(50)
declare pcurr cursor for select ProductName from Products
open pcurr
fetch next from pcurr into @ProductName
while (@@fetch_status = 0)
begin
print (@ProductName)
fetch next from pcurr into @ProductName
end
close pcurr
deallocate pcurr ......
标题 : sql 字符处理函数大全
关键字:
分类 : 个人专区
密级 : 公开
(评分: , 回复: 0, 阅读: 278) »»
SQL字符串处理函数大全(转)2008-04-01 17:21SQL字符串处理函数大全(转)select 字段1 from 表1 where 字段1.IndexOf("云")=1;
这条语句不对的原因是indexof()函数不是sql函数,改成s ......
Oracle 数据库 10g 提供了大量帮助程序(或“顾问程序”),可帮助您决定最佳操作流程。其中一个示例是 SQL Tuning Advisor,它可以提供有关查询调整以及在流程中延长整个优化过程的建议。
但请考虑以下调整案例:假设一个索引确实有助于某个查询,但该查询只执行一次。这样,即使该查询可以得益于此索引,但创 ......
编写一个储存过程usp_GetSortedShippers,它接收Northwind数据库中Shippers表的一个列名称作为其中一个输入(@colname),并从该表返回按输入的列名排序的行。另一个输入(@sortdir)表示排序的方向,‘A’表示按升顺排序,‘D’表示按降序排序。编写该存储过程时要注意它的性能,即,尽可能的使用索引( ......