如何按主题,标记从info_table组获取计数(最大(标记)),标记,主题;

时间:2017-11-28 13:24:54

标签: mysql hive

我需要一个查询,可以显示每个科目的最大分数得分。 据说3名学生的输出需要得分为98分

count marks subject
3      98    Maths    

2 个答案:

答案 0 :(得分:0)

首先找到每个主题的最大标记,并将此结果集用作子查询,并使用EXISTS从具有最大标记的表中查找计数。

<强>查询

select `subject`, 
count(*) as `count`, 
max(`marks`) as `marks`
from `student` t1
where exists(
  select 1 from (
    select `subject`,
    max(`marks`) as `max_marks`
    from `student`
    group by `subject`
  ) t2
  where t1.`subject` = t2.`subject`
  and t1.`marks` = t2.`max_marks`
)
group by `subject`;

答案 1 :(得分:0)

如果你的问题是在Hive上,你可以使用下面的SQL

v_max_marks获取每个主题的最大标记。然后将此视图连接到主表以获取学生计数。

WITH v_max_marks
AS
(SELECT subject, MAX(marks) AS marks
  FROM my_table
 GROUP BY subject)
SELECT my_table.subject, 
       my_table.marks, 
       COUNT(*) AS student_count
  FROM my_table JOIN v_max_marks 
                  ON (my_table.subject = v_max_marks.subject AND 
                      my_table.marks = v_max_marks.marks)
 GROUP BY my_table.subject, 
          my_table.marks;