计算存储过程中的百分比

时间:2013-05-24 03:23:17

标签: sql sql-server tsql stored-procedures

好吧所以我在代码中这样做,我想知道在数据库中做它是否会更好。

SELECT sum(x) as x, sum(y) as y, sum(z) as z from tblRWNPSStat

我想做的是取所有数字的总和

total=x+y+z

然后获取每个变量(x,y,z)的百分比 非常好

x/total*100
y/total*100
z/total*100

是否可以在存储过程中执行此操作?或者我应该坚持代码? 附:我正在使用sqlserver express r2所以解决方案在T-sql中

2 个答案:

答案 0 :(得分:4)

是的,它可以在SP中完成,但您不需要它:

SELECT SUM(X) as X, 
       CAST(SUM(X) AS FLOAT)/CAST(SUM(X+Y+Z) AS FLOAT ) *100 as Per_X,     
       SUM(Y) as Y, 
       CAST(SUM(Y) AS FLOAT)/CAST(SUM(X+Y+Z) AS FLOAT ) *100 as Per_Y, 
       SUM(Z) as Z, 
        CAST(SUM(Z) AS FLOAT)/CAST(SUM(X+Y+Z) AS FLOAT ) *100 as Per_Z
FROM tblRWNPSStat A 

查看sqlfiddle

答案 1 :(得分:2)

是的,您可以使用

创建存储过程
CREATE PROCEDURE PERCENTAGE 
AS
BEGIN
SET NOCOUNT ON;
DECLARE @TOTAL decimal(10,2);
SET @TOTAL = (SELECT SUM(x) + SUM(y) + SUM(z) FROM tblRWNPSStat);
SELECT 
100* SUM(x)/@TOTAL AS [X %], 
100* SUM(y)/@TOTAL AS [Y %], 
100* SUM(z)/@TOTAL AS [Z %], 
@TOTAL AS [TOTAL] FROM 
tblRWNPSStat
END
GO