mySQL - 输出两个计算字段的总和

时间:2014-09-20 11:44:15

标签: mysql

我正在尝试将排名字段转换为总分。例如,我有两个字段,rank1和rank1。

我可以使用以下方法将这些转化为分数:

rank1, 
CASE WHEN rank1=1 THEN 10
            WHEN rank1=2 THEN  6
            WHEN rank1=3 THEN  3
            WHEN rank1=4 THEN  2
            WHEN rank1=5 THEN  1
                        ELSE  0 END  AS score1,
rank2, 
CASE WHEN rank=1 THEN 10
            WHEN rank2=2 THEN  6
            WHEN rank2=3 THEN  3
            WHEN rank2=4 THEN  2
            WHEN rank2=5 THEN  1
                        ELSE  0 END  AS score2,

但是如何输出得分1 +得分2的总和?

我试过了:

SUM(score1 + score2) AS TotalScore,

但它并不喜欢它,因为score1和score2不是表格中的字段。

谢谢!

2 个答案:

答案 0 :(得分:1)

rank1, 
CASE WHEN rank1=1 THEN 10
            WHEN rank1=2 THEN  6
            WHEN rank1=3 THEN  3
            WHEN rank1=4 THEN  2
            WHEN rank1=5 THEN  1
                        ELSE  0 END  AS score1,
rank2, 
CASE WHEN rank2=1 THEN 10
            WHEN rank2=2 THEN  6
            WHEN rank2=3 THEN  3
            WHEN rank2=4 THEN  2
            WHEN rank2=5 THEN  1
                        ELSE  0 END  AS score2,
(CASE WHEN rank1=1 THEN 10
            WHEN rank1=2 THEN  6
            WHEN rank1=3 THEN  3
            WHEN rank1=4 THEN  2
            WHEN rank1=5 THEN  1
                        ELSE  0 END
+
CASE WHEN rank2=1 THEN 10
            WHEN rank2=2 THEN  6
            WHEN rank2=3 THEN  3
            WHEN rank2=4 THEN  2
            WHEN rank2=5 THEN  1
                        ELSE  0 END) as TotalScore

答案 1 :(得分:0)

将SUM()放在CASE语句周围:

SUM(CASE WHEN rank1=1 THEN 10
        WHEN rank1=2 THEN  6
        WHEN rank1=3 THEN  3
        WHEN rank1=4 THEN  2
        WHEN rank1=5 THEN  1
                    ELSE  0 END)  AS score1,
.....