返回Count()

时间:2016-05-01 01:32:47

标签: sql ms-access count min

我正在学习SQL测试,前一年有最后一个问题:

  

为学习论文数量最少的学生命名。多少   他们研究过哪些论文?

到目前为止,这是我创建的选择查询:

select min(Full_Name), min(Amount) 
from (select st.ST_F_Name & ' ' & st.ST_L_Name as Full_Name, count(*) as Amount
from (student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID)
group by st.ST_F_Name & ' ' & st.ST_L_Name)

这非常适合返回我想要的结果,但我不确定这是否是我进行此查询的方式?我觉得在Full_Name上调用min()可能会在某些情况下适得其反。有没有更好的方法来做到这一点? (这是因为未知原因在MS Access中)

2 个答案:

答案 0 :(得分:1)

如果只有一个这样的学生,如果有多个,这可能是最简单的:

select st.ST_F_Name, st.ST_L_Name, count(*) as Amount
from student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
order by Amount ASC LIMIT 1

但是,如果你想找到所有这样的学生,你可以采用不同的方法。我们使用WITH子句来简化事物,定义计算每个学生的课程数量的CTE(公用表表达式)。然后我们选择学生的数量等于CTE中的最小数量:

with per_student as (
select st.ST_F_Name, st.ST_L_Name, count(*) as Amount
from student_course as sc
inner join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
)
select * from per_student 
where amount = (select min(amount) from per_student)

但问题的真正诀窍在于,可能有学生没有参加任何课程。但是到目前为止,你所采用的方法从未见过它们。你想要这样的东西:

with per_student as (
select st.ST_F_Name, st.ST_L_Name, count(sc.SC_ST_ID) as Amount
from student_course as sc
right outer join students as st
on st.ST_ID=sc.SC_ST_ID
group by st.ST_ID
)
select * from per_student 
where amount = (select min(amount) from per_student)

答案 1 :(得分:0)

您可以通过count(*)订购,以便为学生提供最少的论文:

select * from students where st_id in (
    select top 1 sc_st_id 
    from student_course 
    group by sc_st_id
    order by count(*)
)

如果你还需要研究的论文数量,那么加入一个包含最小数量的派生表:

select * from students s
left join (
    select top 1 sc_st_id, count(*)
    from student_course 
    group by sc_st_id
    order by count(*)
) t on t.sc_st_id = s.st_id