编写sql join脚本的任何更清洁或替代方法

时间:2013-08-28 13:57:33

标签: sql sql-server database sql-server-2008 join

我有以下表格:

 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的最大ExamDate。但是在这种聚合方法中使用多个连接是最好的方法吗?或者是否有更清洁的选择。

2 个答案:

答案 0 :(得分: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
             )

答案 1 :(得分: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

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