如何在SQL(Oracle)中使用多个表查找结果集的最高计数

时间:2018-12-08 22:12:55

标签: sql oracle

我有四个桌子。这是骷髅...

ACADEMIC_TBL
    academic_id
    academic_name


AFFILIATION_TBL
    academic_id*
    institution_id*
    joined_date
    leave_date

INSTITUTION_TBL
    institution_id
    institution_name

REVIEW_TBL
    academic_id*
    institution_id*
    date_posted
    review_score

使用这些表,我需要找到具有最多评论数量的学术人员(显示其姓名,而不是ID)和他们当前所属的机构名称(不是ID)。我想这需要使用多个子选择脚本来完成,但是我在弄清楚如何构造它方面遇到了麻烦。

3 个答案:

答案 0 :(得分:0)

您需要一个汇总查询,该查询将所有4个表联接在一起,以计算每位学者进行了多少次审核。

查询:

SELECT
    inst.institution_name, 
    aca.academic_name, 
    COUNT(*)
FROM
    academic_tbl aca
    INNER JOIN affiliation_tbl aff ON aff.academic_id = aca.academic_id
    INNER JOIN institution_tbl inst ON inst.institution_id = aff.institution_id
    INNER JOIN review_tbl rev ON rev.academic_id = aca.academic_id AND rev.institution_id = aff.institution_id
GROUP BY
    inst.institution_name, 
    aca.academic_name,
    inst.institution_id, 
    aca.academic_id

NB:

  • 将学术和机构ID添加到GROUP BY子句中,以防止将具有相同名称的潜在学者或机构(错误地)分组在一起

  • 如果同一位学者对不同机构进行了评论,那么您将为每对学者/机构对找到一行,如果我理解正确,那就是您想要的

答案 1 :(得分:0)

这将起作用:

SELECT   at.academic_name, 
         it.institution_name, 
         Max(rt.review_score), 
from     academic_tbl at, 
         affiliation_tbl afft, 
         institution_tbl it, 
         review_tbl rt 
WHERE    AT.academic_id=afft.academic_id 
AND      afft.institution_id=it.institution_id 
AND      afft.academic_id=rt.academic_id 
GROUP BY at.academia_name,it.instituton_id

答案 2 :(得分:0)

尝试这个:

select
       inst.institution_name
     , aca.academic_name
from
       academic_tbl    aca
     , institution_tbl inst
     , affiliation_tbl aff
     , review_tbl      rev
     , (
              select
                     max(rt.review_score) max_score
              from
                     review_tbl      rt
                   , affiliation_tbl aff_inn
              where
                     rt.date_posted     >= aff_inn.join_date
                     and rt.date_posted <= aff_inn.leave_date
                     and rt.academic_id = aff_inn.academic_id
                     and rt.institution_id  = aff_inn.institution_id
       )
       agg
where
       aca.academic_id         = inst.academic_id
       and inst.institution_id = aff.institution_id
       and aff.institution_id  = rev.institution_id
       and aff.academic_id     = rev.academic_id
       and rev.date_posted    >= aff.join_date
       and rev.date_posted    <= aff.leave_date
       and rev.review_score    = agg.max_score
;

如果有更多相同分数(最高分),它可能会返回不止一名学者。