修改SP的输出

时间:2011-08-01 19:20:17

标签: sql-server

在我的SQl服务器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

抱歉,如果这是一个愚蠢的问题 谢谢 太阳

1 个答案:

答案 0 :(得分: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;