2014-03-05 200 views
0

IAM試圖讓這個SQL計算的百分比爲一組

1.select所有行是[結果]!=成功

2.count每一個獨特的[結果]

3。告訴我多少每個%[結果]從所有取[結果]

似乎是前兩部作品不錯,但最後一列始終是「0」

這是我的查詢:

SELECT [result] , COUNT(*) AS Total,(
              COUNT(*)/
              ( 
               SELECT COUNT(*) 
               FROM[my_table] 
              ) 
             ) * 100 AS '%' 

             FROM [my_table] 
              WHERE ([result]!='Success') 
              GROUP BY [result] 

這就是結果:

enter image description here

罐大家!

回答

1

您需要將數字轉換爲小數或浮點數,否則您將以整數進行操作。

SELECT [result] , COUNT(*) AS Total, 
     (1.0 * COUNT(*)/( 
      SELECT COUNT(*) 
      FROM[my_table] 
      ) 
    ) * 100 AS '%' 
FROM [my_table] 
WHERE ([result]!='Success') 
GROUP BY [result] 
0

我想試試這個:

select [result], count(1) over (partition by [result]), 
    (count(1) over (partition by [result]) * 100/count(*)) 
    FROM [my_table] 
    WHERE ([result]!='Success') 

我覺得你的代碼的工作,雖然,我認爲你需要* 100你把之前,我想你發現一個問題與使用int和具有值< 1,所以四捨五入爲0

0

這應該這樣做,只要在第一個數字是一個浮動的結果將是一個浮子

SELECT [result] 
    ,COUNT(*) AS Total 
    ,CAST((COUNT(*)AS FLOAT)/(SELECT COUNT(*) FROM [my_table])) AS '%' 
    FROM [my_table] 
    WHERE ([result]!='Success') 
    GROUP BY [result]