2014-04-02 18 views
0

我想在列上使用公式,我想要的是我在列中有一个值我想将它乘以(100/SumofColumnValues)我成功了到现在为止是让伯爵使用SQL Server列值的公式并将其存储在新列

select 
    Count(*) as ResponseCount, 
    PropertyValue As Answer 
from 
    table 
where 
    Questionid = 42 and formid = 1 
group by 
    propertyvalue 

的总和这给像这样

ResponseCount Answers 
    34  One 
    100  Two 

,然后使用CTE:

With Temp As (
    select 
     PropertyValue As Answers, 
     Count(*) As ResponseCount 
    from 
     questionerdetail 
    where 
     Questionid = 42 and formid = 1 
    group by 
     PropertyValue 
) 
select Sum(ResponseCount) As Total 
from Temp 

我得到

Total 
134 

我需要的是

ReponseCount Answer ResponsePercentage 
    34  One  25.37  TheFormula will be 34*(100/134)- (134 is the total sum of responsecount) 
    100  Two  74.62  TheFormula Will be 100*(100/134) 
+0

MS Sql 2012对不起! –

回答

2

或者,如果你想使用分析功能,而不是子选择:

select 
    Count(*) as ResponseCount, 
    PropertyValue As Answer , 
convert (dec(28,2) ,Count(*))*100/(sum(count(*)) over()) as ResponsePercentage 
from 
    table 
where 
    Questionid = 42 and formid = 1 
group by 
    propertyvalue 

(转换功能SQL Server语法)

1
select 
    Count(*) as ResponseCount, 
    PropertyValue As Answer , 
Count(*)*100/(select count(*) from table) as ResponsePercentage 
from 
    table 
where 
    Questionid = 42 and formid = 1 
group by 
    propertyvalue 
+0

这是完美的唯一的问题,我得到的是响应百分比是int,所以.94变为0否则一切都是完美的。 –

相关问题