sql查询来计算加权点

时间:2013-10-22 02:03:03

标签: sql group-by weighted

我有一个数据库,用于存储等级为a,b,c的论坛帖子。我想为a级分配3分,为b级分2分,为c级分1分,并获得所有用户的总分。如果权重是偶数,我可以使用此查询:

select count(*), userId from table_post group by userId;

但如何在一个查询中计算加权帖子?字段是post_id,user_id,grade,post_content

1 个答案:

答案 0 :(得分:0)

SELECT A.USER_ID,SUM(NEW_POINTS)
FROM
(
SELECT USER_ID,
       CASE WHEN grade = 'a'
            THEN points=3
            WHEN grade = 'b'
            THEN points=2
            WHEN grade = 'c'
            THEN points=1
            END AS new_points
FROM table_post
) A   
GROUP BY A.USER_ID;