2

我需要找到还书平均失踪天数最高的学生。我有 2 张桌子:

  • 用户 -> id、fname、lname、专业
  • 借出 -> isbn(书号), id, since(date), due(date), actual(date)

这是我这样做的方法,带有子查询

select concat(fname, '', lname) as name 
  from users 
 where id in ( select id 
                 from loaned 
                group by id 
               having avg(datediff(due, actual))
                      = ( select min(m) 
                            from ( select avg(datediff(due, actual)) as m 
                                     from loaned
                                    group by id 
                                          ) as minavg
                                  )
                      );

我怎么能用 JOIN 解决这个问题?

4

1 回答 1

1
select concat(fname, '', lname) as name 
from users u
join loaned l on l.id = u.id and due < actual
group by 1
order by avg(actual - due) desc
limit 1

此查询仅获取迟到书籍的平均值,而不是整体平均值。对于总体平均删除and due < actual


要返回具有相同最高平均数的所有学生:

select concat(fname, '', lname) as name 
from users u
join loaned l on l.id = u.id and due < actual
group by 1
having avg(actual - due) = (
    select avg(actual - due)
    from loaned
    where due < actual
    group by id
    order by 1 desc
    limit 1)
于 2013-09-21T14:55:18.720 回答