2013-11-21 184 views
0

我正在SQL Server中構建一個查詢,計算我們爲調查收到的分數。我們有一個名爲overall_score的專欄,用戶輸入1-5的數字作爲評分。我正在嘗試創建一個存儲過程,根據分數計算評分。SQL Server 2012查詢計算計算

Score rating = (Total count of scores 4 and 5)/(Total number of responses) * 100 

我有創造的結果,我需要三個獨立的select語句,但是當我去他們結合在一起我的輸出爲0

是否有人可以指導我什麼,我做錯了什麼?

單獨的SQL語句:

SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 4; 
SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 5; 
SELECT count(overall_score) FROM Layer1_DataMerge; 

結合在一起:

SELECT distinct 
( 
    (
     (SELECT count(overall_score) FROM Layer1_DataMerge WHERE Overall_Score = 4) + 
     (SELECT count(overall_score) FROM Layer1_DataMerge WHERE overall_score = 5) 
    )/(SELECT count(overall_score) FROM Layer1_DataMerge) 
) AS CSAT 
FROM Layer1_DataMerge; 

回答

2

原因你得到零是因爲你做整數師。隨着整數除法1/3 = 0。你需要轉換爲浮點運算,再加上你可以做到這一切在一個查詢:

SELECT 100.0 * 
     (SUM(CASE WHEN overall_score = 4 THEN 1 ELSE 0 END) + 
     SUM(CASE WHEN overall_score = 5 THEN 1 ELSE 0 END))/
     COUNT(overall_score) 

SELECT 100.0 * 
     SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END)/
     COUNT(overall_score) 

,只顯示2位小數你可以轉換爲數值型與2位小數:

SELECT CAST(
     100.0 * 
     SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END)/
     COUNT(overall_score) 
     AS NUMERIC(5,2)) 

或者使用STR轉換爲字符串:

SELECT STR(
     100.0 * 
     SUM(CASE WHEN overall_score IN (4,5) THEN 1 ELSE 0 END)/
     COUNT(overall_score) 
     ,5,2)  
+0

太棒了!這工作,非常感謝你。現在我唯一的問題是我無法獲得正確的小數位數。我認爲結果只會顯示您在乘數中的小數位數。當我使用100.0或100.00時,我仍然得到相同的答案0.62044589450,我只希望它顯示0.62 .... –

+0

@JaimieeBayliss更新了我的答案,顯示2位小數。 –

+0

再次非常感謝你!這真的有幫助。 –