1

我有以下表格:

 Table2       
 StudentNumbers  ExamType
 ------------------------
           1234         1
           2343         2   
           3345         5
           3454         1
           5465         2
            ...

 Table1   
 StudentNumbers  ExamType   ExamDate  School  Area             Info
 ------------------------------------------------------------------
           1234         1       0825  warren    ny    0x504B03042D0
           1234         1       0829   north    nj    0x63D86E1FFFF
           1233         2       0921   north    nj    0xA001400646F
           2343         1       0922  warren    ny    0x01400646174
           2343         1       0925   north    ny    0x100100070se
            ...

我正在尝试编写查询以获得以下结果:

StudentNumbers  ExamType   ExamDate  School  Area            Info
-----------------------------------------------------------------
          1234         1       0829   north    nj   0x63D86E1FFFF
          2343         1       0925   north    ny   0x100100070se

我写了以下查询:

Select t1.StudentNumbers, t1.ExamDate, t1.School, t1.Info, t1.ExamType        
from Table1 as t1
  Join(
       Select ts.StudentNumbers, max(ts.ExamDate) as ExamDate
       from Table2 as ts
         Join Table1 as pl on 
           ts.StudentNumbers = pl.StudentNumbers where ts.ExamType = pl.ExamType
       group by ts.StudentNumbers
       ) as t2 on t1.StudentNumbers = t2.StudentNumbers
                    and t1.ExamDate = t2.ExamDate

上面的查询有效,并给出了我想要的结果,即基于 Table2 的特定 ExamType 的 max ExamDate。但是在这种聚合方法中使用多个连接是最好的方式吗?或者有没有更清洁的选择。

4

2 回答 2

0

您的查询很好,但我认为在子查询之外使用 Table2 表会是更好的选择。

SELECT *
FROM (
      SELECT StudentNumbers, ExamType, MAX(ExamDate) AS ExamDate
      FROM Table1
      GROUP BY StudentNumbers, ExamType
      ) t1 JOIN Table1 t2 ON t1.StudentNumbers = t2.StudentNumbers
             AND t1.ExamType = t2.ExamType AND t1.ExamDate = t2.ExamDate
WHERE EXISTS(
             SELECT 1
             FROM Table2 t3
             WHERE t1.StudentNumbers = t3.StudentNumbers
               AND t1.ExamType = t3.ExamType
             )
于 2013-08-28T19:59:17.037 回答
0
SELECT
    t1.*
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.StudentNumbers = t2.StudentNumbers
WHERE t1.ExamDate = (SELECT MAX(ExamDate) FROM Table1 WHERE StudentNumbers = t1.StudentNumbers)
ORDER BY t1.StudentNumbers ASC

虽然可能不是最有效的解决方案。

于 2013-12-20T09:29:36.143 回答