将数字格式化为货币金额

Posted

技术标签:

【中文标题】将数字格式化为货币金额【英文标题】:Formatting number as currency amount 【发布时间】:2018-09-30 02:01:17 【问题描述】:

我想为我的 SQL 比萨餐厅数据库创建一个“销售报告”。当我尝试使用 sum(order_amount) 运行 SELECT 查询时,该列未格式化。我正在使用 Oracle SQL。代码如下:

column order_amount heading "Order Amount" format '$9,999,999.00';
select order_id, count(order_id) as "Number of Orders", sum(pizza_quantity) as "Pizzas Sold", 
sum(order_amount) as "Total Profit"
from order_details group by order_id;

这是输出:

SQL> select order_id, count(order_id) as "Number of Orders",sum(pizza_quantity) as "Pizzas Sold",
  2  sum(order_amount) as "Total Profit"
  3  from order_details group by order_id;

  Order ID Number of Orders Pizzas Sold Total Profit
---------- ---------------- ----------- ------------
         1                2           5          105
         6                1           2           20
         2                2           6          165
         4                2          12          130
         5                2           6           80
         8                1           7          140
         3                2           4           80
         7                1           6          120
         9                1           8          120
        10                1           9          270

10 rows selected.

有什么方法可以显示格式为货币的总利润列?

【问题讨论】:

【参考方案1】:

您可以尝试使用to_char()

...
to_char(sum(order_amount), '$9,999,999.00')
...

【讨论】:

【参考方案2】:

您可以将数字格式建模元素用作FML9,999.99$9G990D00 作为to_char 函数的第二个参数,如下例所示:

SQL> alter session set nls_currency='$';
SQL> alter session set NLS_NUMERIC_CHARACTERS = '.,';
SQL> with tab(order_ID,order_amount) as
  (
    select 1,255.51 from dual union all
    select 1,750.33 from dual union all    
    select 6,420.39 from dual union all
    select 2,790.00 from dual union all
    select 2,375.05 from dual    
  )
  select to_char(sum(order_amount),'FML9,999.99') as "Total Profit" 
    from tab
   group by order_ID  
  union all
  select to_char(sum(order_amount),'$9G990D00') as "Total Profit" 
    from tab
   group by order_ID

Total Profit
$1,005.84
$420.39
$1,065.05
 $1,005.84
   $420.39
   $1,065.05

Rextester Demo

【讨论】:

【参考方案3】:

如果您的问题是关于 SQL*Plus 列格式的具体问题,那么问题是您为名为 order_amount 的列定义了一种格式,但在查询中它被称为 "Total Profit"

column order_amount heading "Order Amount" format '$9,999,999.00'

如果您更改查询以将所需列命名为 order_amount,则将使用定义的格式:

select order_id, count(order_id) as "Number of Orders", sum(pizza_quantity) as "Pizzas Sold"
     , sum(order_amount) as order_amount
from   order_details
group by order_id;

(顺便说一句,我怀疑订单总额是否都是利润,除非您的成本为零,在这种情况下,我想投资您的披萨业务。)

【讨论】:

以上是关于将数字格式化为货币金额的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 javascript/jquery 将数字格式化为印度货币(在数据表中)

如何仅使用货币代码将数字格式化为货币?

如何将数字格式化为货币字符串

将数字数组格式化为具有最小宽度的货币

将具有多个小数位的数字格式化为货币

PHP number_format():将数字四舍五入,然后格式化为货币