select time_slot_id, MAX(student_num) as max_num
from (select COUNT(takes.ID)as student_num, time_slot_id
      from takes, section
      where takes.course_id=section.course_id 
      group by time_slot_id) as num_slot(student_num, time_slot_id);
      
刚学SQL的菜鸟,这地方老报错,不知道为什么,求各位大神解释

解决方案 »

  1.   

    select time_slot_id, MAX(student_num) as max_num
    from (
    select COUNT(takes.ID)as student_num, time_slot_id
      from takes, section
      where takes.course_id=section.course_id  
      group by time_slot_id
    ) as num_slot
    group by time_slot_id
      

  2.   

    如果select里面没有用max、sum、count、min、avg这些的列,都要在group by中出现,另外,其实sql语句的执行顺序不是你写代码的顺序,是先group by 再select的,如果group by中都没有出现这列,select的时候肯定报错。
      

  3.   

    这样改的话就不是不是我要的查询结果了,我只要student_num最大的那个元组就行了,如果按再按time_slot_id分组的话,就是把子查询的结果再输出一遍
      

  4.   

    group by只是在from的子查询里,对外层的查询也有影响吗?
      

  5.   

    select top 1 COUNT(takes.ID)as student_num, time_slot_id
      from takes, section
      where takes.course_id=section.course_id  
      group by time_slot_id
    order by student_num desc
      

  6.   


    group by 的语法规则就是所有查询结果不是聚集函数的项都要出现在group by 中
    建议给出表数据和期望结果。
      

  7.   

    我懂了,是我把group by的语法理解错了,谢谢各位大神了~~