我有简单的SQL:
SELECT Count(c.[id]) 'Count'
,Count(c.[phone_home]) 'phone_home '
,CAST(Count(c.[phone_home])*100/Count(c.[id]) as decimal(18,2)) '%'
,Count(c.[phone_other]) 'phone_other '
,CAST(Count(c.[phone_other])*100.0/Count(c.[id]) as decimal(18,2) ) '%'
,Count(c.[primary_address_state]) 'primary_address_state '
,CAST(Count(c.[primary_address_state])*100/Count(c.[id]) as DECIMAL(18,2)) '%'
FROM [sugarcrm_cmsru_dev].[dbo].[contacts] c
我注意到百分比的计算不正确。对于这个表达式:
CAST(Count(c.[phone_other])*100.0/Count(c.[id]) as decimal(18,2) ) '%'
结果为0.24
对于这个表达式:
CAST(Count([primary_address_state])*100/Count(c.[id]) as decimal(18,2)) '%'
结果为0,00
但表达方式彼此相同。怎么了?
答案 0 :(得分:2)
CAST(计数(c。[phone_other]) * 100.0 /计数(c。[id])为十进制(18,2))'%'
CAST(Count([primary_address_state]) * 100 / Count(c。[id])为十进制(18,2))'%'
您的区别在于粗体,您需要将第二个100更改为100.0,SQL将第一个解释为数字,因此将答案作为数字给出,但第二个被解释为整数,因此答案是(舍入的)整数