代码之家  ›  专栏  ›  技术社区  ›  Maxcot

如何计算只返回最新项的所有子查询结果?

  •  0
  • Maxcot  · 技术社区  · 6 年前

    Adding a Query to a Subquery then produces no results )@D-Shih提供了一个很好的解决方案,我想扩展一下。

    我正试图解决 <???> AS CountOfReports, 下面一行,但是我的SQL技能没有那么好。

    SELECT 
        t.NAME,
        t1.REPORTINGTYPE,
         <???> AS CountOfReports,     <<<< ****
        t1.REPORTINGPERIOD 
    FROM 
        teachers AS t 
    INNER JOIN
        (SELECT 
             *,
             (SELECT COUNT(*) FROM REPORTS tt 
              WHERE tt.TEACHER_ID = t1.TEACHER_ID 
                AND tt.REPORTINGPERIOD >= t1.REPORTINGPERIOD) rn
         FROM 
             REPORTS t1) AS t1 ON t1.TEACHER_ID = t.id AND rn = 1
    ORDER BY 
        t.NAME
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   CL.    6 年前

    你可以用 correlated subquery :

    SELECT t.Name,
           r.ReportingType,
           max(r.ReportingPeriod),
           (SELECT count(*)
            FROM Reports r2
            WHERE r2.Teacher_ID = r.Teacher_ID
           ) AS Reports
    FROM Teachers t
    JOIN Reports r ON t.ID = r.Teacher_ID
    GROUP BY r.Teacher_ID;
    
    NAME            REPORTINGTYPE  max(r.ReportingPeriod)  Reports   
    --------------  -------------  ----------------------  ----------
    Mr John Smith   Final          2017-03                 3         
    Ms Janet Smith  Draft          2018-07                 2