使用任意数量的小数位格式化SQL数字查询结果 [英] Formatting an SQL numeric query result with an arbitrary number of decimal places

查看:322
本文介绍了使用任意数量的小数位格式化SQL数字查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下两列的数据库表:


  • 金额:数字(18,0)

  • DecimalPlaces:numeric(18,0)


    该表格可以存储各种货币的金额,金额(我不能改变这个数据模型)。例如,可能有两行是这样的:




    • 1290,2(这是£12.90,需要显示为12.90)

    • 3400,0(这是3400日元,需要显示为3400)


      <我需要一个SQL查询为Oracle和SQL Server,将格式化每个数量正确的小数位数,保留任何尾随零如上所示。我不能使用存储过程,报表工具或Excel。 解决方案

你的问题是,没有一个简单的在一个查询中为SQLServer和Oracle执行此操作的方法。



正确的方法是使用STR:

 从myTable中选择STR(Amount,18,DecimalPlaces); 

对于Oracle来说,正确的方法是使用to_char:

  SELECT to_char(amount,'99999999999999.'|| rpad('',DecimalPlaces,'0'))$ My 
;

jms和Andrew提供的查询在Oracle查询中不起作用,因为Oracle SQL使用LENGTH )不是LEN()。而Oracle使用to_char()不是Cast()。

I have a database table with these two columns:

  • Amount: numeric (18,0)
  • DecimalPlaces: numeric (18,0)

This table can store amounts in various currencies, with the decimal place removed from the amount (I can't change this data model). For example, there might be two rows like this:

  • 1290, 2 (This is £12.90, needs to appear as "12.90")
  • 3400, 0 (This is 3400 Japanese Yen, needs to appear as "3400")

I need an SQL query for both Oracle and SQL Server that will format each amount with the correct number of decimal places, preserving any trailing zeroes as illustrated above. I can't use stored procedures, a reporting tool, or Excel.

解决方案

Your problem is that there isn't an easy way to do this for both SQLServer and Oracle in one query.

The Correct way to do this for SQLServer is to use STR:

Select STR(Amount, 18, DecimalPlaces) from myTable;

The correct way to do this for Oracle is using to_char:

SELECT to_char (amount, '99999999999999.'||rpad('',DecimalPlaces, '0')) 
from MyTable;

The queries presented by jms and Andrew won't work in an Oracle query because Oracle SQL uses LENGTH() not LEN(). And Oracle uses to_char() not Cast().

这篇关于使用任意数量的小数位格式化SQL数字查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆