2017-06-21 17 views
0

这里是我们的餐桌如何获得SQL不同的主题标志的基础上,责令学生排名

name   math  physics  chemistry hindi english 
pk   85  65   45   54  40 
ashis  87  44   87   78  74 
rohit  77  47   68   63  59 
mayank  91  81   78   47  84 
komal  47  51   73   61  55 

我们希望结果表明为(基本上是总结成绩)

rank name   total 
1  mayank  381 
2  ashis   370 
3  rohit   314 
4  pk   289 
5  komal   287 
+0

[如何在SQL查询中SUM两个字段(HTTPS的可能重复:// stackoverflow.com/questions/14877797/how-to-sum-two-fields-within-an-sql-query) – Henry

+0

请显示您的代码以获得高质量的答案。 – TomServo

回答

0

尝试这

SELECT @curRank := @curRank + 1 AS rank, name, (math + physics + chemistry + hindi + history) AS total FROM table, (SELECT @curRank := 0) r ORDER BY total DESC; 

这将总结所有的领域,并按降序排序,并添加一个排名。

通过做SELECT @curRank := 0您可以将它全部保留在一个SQL语句中,而无需首先执行SET。

0
SET @rank=0; 

SELECT @rank:[email protected]+1 AS rank,name,(math+physics+chemistry+hindi+english) as total 
FROM tablename ORDER BY total DESC 

这将产生你想要的结果

rank | name | total 

-------------------- 
1 | mayank | 381 
2 | ashis | 370 

更多细节看看mysql ranking results

+0

很好的答案!你可以在我回答的时候在一个SQL语句中处理这个,只是一个小诀窍要知道。 – Henry

+0

是的,那家伙似乎是新来的sql,所以我不想复杂化。 @名称 – vijay

+0

感谢您的帮助 –