SQL查询从重复行获取唯一值

时间:2014-12-03 14:47:46

标签: mysql sql

我在桌子上:

Roll_No Subject  Marks  Percentage
1       Maths    75     70
1       Science  70     70
1       History  65     70
2       Maths    89     90
2       Science  91     90
2       History  90     90
3       Maths    50     55
3       Science  55     55
3       History  60     55

我想在第一个查询中获得2个输出:

Roll No sum(marks)  Percentage
1       210         70
2       270         90
3       165         55

我想从基表获得第二个输出: Count(roll_no),Sum(Marks),Sum(Percentage ---这应该是一个学生的一个值)。

3    645(sum of all marks)    215 (i.e 70+90+55)  

您能帮助我或指导我取得成果。

3 个答案:

答案 0 :(得分:0)

select Roll_No,Sum(Marks),Max(Percentage) from table group by Roll_No;

with cte as
(
select Roll_No,Sum(Marks) as Marks ,Max(Percentage) as Percent from table group by Roll_No
)
select count(Roll_No),Sum(Marks),Sum(Percent) from cte;

答案 1 :(得分:0)

您应该使用GROUP BYSUM功能。我认为这应该有所帮助:

SELECT Roll_No, SUM(Marks), Percentage FROM table GROUP BY Percentage

答案 2 :(得分:0)

类似的东西:

select roll_no, sum(marks), max(percentage)
from table
group by roll_no

问题的第二部分:

select count(roll_no), sum(marks), max(percentage)
from (select roll_no, sum(marks) as marks, max(percentage) as percentage
      from table
      group by roll_no)