2011-08-01 50 views
0

在我的SQl服務器Sp。修改SP的輸出

`SELECT rating as [Rating],count(id) as [RatingCount] 
FROM MMBPollResults 
where mmb_id = @MMbid 
GROUP BY rating 

This SP returns the rating for each user. 
i:e rating ratingcount 
` 1   2 
    2   1 
    5   4 

因此,這意味着

2users have rated the transaction with 1star 
1 user has rated the transaction with 2stars 
4 users have rated the transaction with 5stars 

這是我所需要的輸出

rating ratingcount 
` 1   2 
    2   1 
    3   0 
    4   0 
    5   4 

對不起,如果這是一個愚蠢的問題 感謝 孫

+0

是什麼在MMBPollResults的數據是什麼樣子?你有沒有一個查找表的所有可能的收視率? –

回答

3

您需要1到5的表格。這可以是數字表格或其他評分表。

這裏我用一個簡單的UNION,使表1〜5

SELECT 
    List.Rating, 
    count(MMB.*) as [RatingCount] 
FROM 
    (
    SELECT 1 AS Rating 
    UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 
    ) List 
    LEFT JOIN 
    MMBPollResults MMB ON List.Rating = MMB.Rating AND MMB.mmb_id = @MMbid 
GROUP BY 
    List.Rating 
ORDER BY 
    List.Rating;