为什么在此T-SQL查询中无法获得正确的百分比值?

时间:2019-03-01 05:29:56

标签: sql-server tsql

我正在使用SQL Server 2014,并且有以下T-SQL查询:

select 
     xx.[Market],
     xx.[RN],
     xx.[Total],
cast(CAST(((xx.[RN]/xx.[Total])) AS DECIMAL(19,2)) as varchar(10))+ ' ' + '%'  as [Percentage] 

from

(
select distinct Market, 
       sum(rn) over (partition by market) as [RN], 
       sum(rn) over () as [Total]

from [View1]
)xx

上述查询的输出如下:

 Market   RN    Total   Percentage
 UK       50     200     0.00 %
 France   25     200     0.00 %
 Germany  125    200     0.00 %

为什么百分比显示不正确?

我期望以下输出:

Market   RN    Total   Percentage
 UK       50     200     25.00 %
 France   25     200     12.50 %
 Germany  125    200     62.50 %

1 个答案:

答案 0 :(得分:0)

您可能需要明确地将百分比的分子或分母设为双精度类型:

SELECT
    xx.[Market],
    xx.[RN],
    xx.[Total],
    CAST(CAST(1.0*xx.[RN] / xx.[Total] AS DECIMAL(19,2)) AS varchar(10)) + ' ' + '%' AS [Percentage] 
--            ^^^ change here
FROM
(
     SELECT DISTINCT
         Market, 
         SUM(rn) OVER (PARTITION BY Market) AS [RN],
         SUM(rn) OVER () AS [Total]
    FROM [View1]
) xx;