sql-server-2008 – TSQL将总和转换为Money

前端之家收集整理的这篇文章主要介绍了sql-server-2008 – TSQL将总和转换为Money前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用sql Server 2008,我试图让其中一些列返回$xxx,xxx.xx

这是我正在使用的查询(此查询然后一些更新只是为了计算数字并在结尾选择## tempshow)

  1. SELECT
  2. CASE GROUPING(s.StoreID) WHEN 1 THEN '' ELSE s.StoreID END [StoreID],CASE GROUPING(p.VendorID) WHEN 1 THEN '' ELSE p.VendorID END [VendorID],SUM(d.Quantity) AS [UnitSold],CAST(SUM(d.amount * d.quantity) AS DECIMAL(18,2)) AS Amount,CAST(SUM(d.Discount) AS DECIMAL(18,2)) AS Discount,CAST(SUM((d.Amount * d.Quantity - d.Discount)) AS DECIMAL(18,2)) AS ExtSold,CAST(SUM(d.Cost * d.Quantity) AS DECIMAL(18,2)) AS Cost,CAST(0 AS DECIMAL(18,2)) AS Profit,2)) AS OnHand,2)) AS OnHandRetail,2)) AS OnHandCost,2)) AS ReceivedCost,2)) AS ReceivedRetail,2)) AS ReceivedQty,2)) AS Margin,CAST(0 AS DECIMAL(12,2)) AS TurnOver,CAST(0 AS INTEGER) AS OnOrder
  3. INTO
  4. ##tempshow
  5. FROM
  6. RPTrs s,RPTrsd d,RPIv i,RPProducts p
  7. WHERE
  8. s.ReceiptNO = d.ReceiptNO and
  9. s.StoreID = d.StoreID and
  10. i.UPC = d.UPC and
  11. i.StoreID = d.StoreID and
  12. p.ProductID = i.IVProduct and
  13. s.StoreID = '01' and
  14. s.TRSDate > GETDATE()-20 and
  15. p.Service = 0
  16. GROUP BY
  17. GROUPING SETS((s.StoreID,p.VendorID),())

哪个回报:

我试过了

CAST(SUM(d.amount * d.quantity)AS MONEY)作为金额,

SUM(CAST((d.amount * d.quantity)AS MONEY))AS金额,

预期输出(加上与此Amount列相同的其他列):

  1. |StoreID | VendorID | UnitSold | Amount
  2. ---------------------------------------------
  3. 1 | 01 | 0000 | 0 | $0.00
  4. 2 | 01 | am | 62 | $6,275.00
  5. 3 | 01 | AO | 58 | $18,964.00
  6. 4 | 01 | payless | 6 | $1,383.36
  7. 5 | | | 126 | $26,622.36

我需要Amount,Discount,ExtSold,Cost,Profit,OnHandRetail,OnHandCost,ReceivedCost,ReceivedRetail为货币格式

解决方法

这是应该在表示层上完成的,但是如果你需要在sql中执行此操作,则可以使用:
  1. '$'+convert(varchar(50),CAST(amount as money),-1) amount

这是一个例子:

  1. ;with cte (amount)
  2. as
  3. (
  4. select 123254578.00 union all
  5. select 99966.00 union all
  6. select 0.00 union all
  7. select 6275.00 union all
  8. select 18964.00 union all
  9. select 1383.36 union all
  10. select 26622.36
  11. )
  12. select '$'+convert(varchar(50),-1) amount
  13. from cte

SQL Fiddle with Demo.这将返回:

  1. | AMOUNT |
  2. -------------------
  3. | $123,254,578.00 |
  4. | $99,966.00 |
  5. | $0.00 |
  6. | $6,275.00 |
  7. | $18,964.00 |
  8. | $1,383.36 |
  9. | $26,622.36 |

注意:这在sql Server 2012中会更容易,因为您可以使用FORMAT()

  1. ;with cte (amount)
  2. as
  3. (
  4. select 123254578.00 union all
  5. select 99966.00 union all
  6. select 0.00 union all
  7. select 6275.00 union all
  8. select 18964.00 union all
  9. select 1383.36 union all
  10. select 26622.36
  11. )
  12. select '$'+FORMAT(amount,'#,0.0000') amount
  13. from cte

SQL Fiddle with Demo

猜你在找的MsSQL相关文章