SQL Cast显示小数

时间:2018-04-19 13:41:59

标签: sql sql-server casting smss

我的select子句中有以下语句;

(([Complt_Emp] + [No_Non_Complt_Emp])/ [No_of_Emp]) as Total_Completed

如何实现CAST“cast(your_float_column as decimal(10,2))”?我希望我的列Total_Completed显示2位小数

我似乎无法获得正确的语法!

谢谢

4 个答案:

答案 0 :(得分:2)

计算结果取决于使用的列类型。

如果你划分int列,你得到int结果:1 / 6 = 0

将每个值转换为十进制时,结果为:1 / 6 = 0.1666666666666

现在您需要2个十进制结果,因此您必须convert / round以前的结果才能获得预期值

请参阅小提琴,了解除法和演员/圆形的一些例子:http://sqlfiddle.com/#!18/51785/5

一个简单的技巧可以使用:

round ( 1.0 * ( [Complt_Emp] + [No_Non_Complt_Emp] ) / [No_of_Emp] , 2 )

答案 1 :(得分:1)

我怀疑你的所有值都是INT。 int除以int将返回int。

(([Complt_Emp] + [No_Non_Complt_Emp])/ cast([No_of_Emp] as decimal(10,2)) as Total_Completed

答案 2 :(得分:1)

单独投射每个表达

CAST(([Complt_Emp] + [No_Non_Complt_Emp]) as decimal(10,2)) /
CAST([No_of_Emp] as decimal(10,2)) as Total_Completed

答案 3 :(得分:0)

试试这个

SELECT PRIMARY_OWNER AS 'Taxpayer Name / Doing Business As',
   BILL_NUMBER AS 'Taxpayer Id / Bill Number',
   IN_CARE_OF_NAME AS 'In Care Of',
   ADDRESS_LINE1 AS 'Address Line 1',
   ADDRESS_LINE2 AS 'Address Line 2',
   ADDRESS_LINE3 AS 'Address Line 3',
   CITY AS 'City',
   RIGHT(STATE, 2) AS 'State',
   POSTAL_CODE AS 'Zip',
   PWA.BILLING_DATE AS 'Bill Date',

   sum(Tax Paid), 
   sum(Interest Paid), 
   sum(Penalty Paid),
   sum(Balance Due)

   CASE
       WHEN LEVY_TYPE_CODE IS NULL
            AND SUB_TRANSACTION_TYPE = 'BILLALLOCATION'
            AND LEVY_TYPE = 'LEVTTAX'
       THEN DIS.AMOUNT
       ELSE '0.00'
   END AS 'Tax Paid',
   CASE
       WHEN LEVY_TYPE_CODE = 'LEVTINTEREST'
            AND SUB_TRANSACTION_TYPE = 'BILLALLOCATION'
       THEN DIS.AMOUNT
       ELSE '0.00'
   END AS 'Interest Paid',
   CASE
       WHEN LEVY_TYPE_CODE IS NULL
            AND LEVY_TYPE = 'LEVTLLFEE'
            AND SUB_TRANSACTION_TYPE = 'BILLALLOCATION'
       THEN DIS.AMOUNT
       ELSE '0.00'
   END AS 'Penalty Paid',
   CASE
       WHEN SUB_TRANSACTION_TYPE = 'PAYMENTRELEASE'
       THEN DIS.AMOUNT
       ELSE '0.00'
   END AS 'Amount Released',
   CURRENT_BILL_DUE_AMOUNT AS 'Balanace Due'
FROM EXTBLM_BILL_MASTER AS PWA
 INNER JOIN PTABLM_BILL_MASTER AS BILL ON PWA.BILL_PK = BILL.BILL_PK
 LEFT OUTER JOIN PTASBT_SUBTRANSACTION AS SBT ON BILL.BILL_PK =     SBT.ALLOCATION_TYPE_REFERENCE_ID
 LEFT OUTER JOIN PTADIS_DISTRIBUTION AS DIS ON SBT.SUBTRANSACTION_PK = DIS.SBT_SUBTRANSACTION_PK
 LEFT OUTER JOIN PTAGLA_GL_ALLOCATION AS GL ON DIS.GLA_GL_CODE_ALLOCATION_ID = GL.GL_CODE_ALLOCATION_ID
 LEFT OUTER JOIN PTALAC_LEVY_ACCOUNT AS PAYLAC ON GL.ACCOUNT_ID = PAYLAC.LEVY_ACCOUNT_PK
WHERE BASE_NUM = '0000793569'
  AND PAYLAC.TAX_DISTRICT = 'JURSBUN'
  AND TAX_YEAR = 2017;
Group by PRIMARY_OWNER, 
   BILL_NUMBER,
   IN_CARE_OF_NAME,
   ADDRESS_LINE1,
   ADDRESS_LINE2,
   ADDRESS_LINE3,
   CITY,
   STATE,
   POSTAL_CODE,
   PWA.BILLING_DATE