加入两个或多个表时,只获得最大ID

时间:2015-12-30 10:04:02

标签: sql-server sql-server-2008

我有一个sql小提琴。 http://sqlfiddle.com/#!3/c92c75/4

我有两个查询,显示输出。

SELECT (A.EMP_ID),A.EMP_NAME, A.EMP_NO, C.MAINT_CHANGE, 
          C.MAINT_ID FROM EMPLOYEE_MASTER A   LEFT OUTER JOIN DESIGNATION_MAINTENANCE C ON A.EMP_ID = C.EMP_ID 
             AND C.MAINT_ID =(select top(1) MAINT_ID from DESIGNATION_MAINTENANCE order by MAINT_ID DESC)


 SELECT (A.EMP_ID),A.EMP_NAME, A.EMP_NO, C.MAINT_CHANGE, 
          C.MAINT_ID FROM EMPLOYEE_MASTER A  LEFT OUTER JOIN DESIGNATION_MAINTENANCE C ON A.EMP_ID = C.EMP_ID 

实际输出我需要的是

EMP_ID  EMP_NAME    EMP_NO  MAINT_CHANGE    MAINT_ID
17  EMPLOYEE17 MNAME17 MNAME18  17  (null)  (null)
18  EMPLOYEE18 MNAME18 MNAME19  18  February, 28 2015 00:00:00  3
19  EMPLOYEE19 MNAME19 MNAME20  19  (null)  (null)
20  EMPLOYEE20 MNAME20 MNAME21  20  (null)  (null)
21  EMPLOYEE21 MNAME21 MNAME22  21  December, 01 2014 00:00:00  5

如何编写查询?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT (A.EMP_ID),A.EMP_NAME, A.EMP_NO, C.MAINT_CHANGE, 
C.MAINT_ID FROM EMPLOYEE_MASTER A
LEFT OUTER JOIN DESIGNATION_MAINTENANCE C
    ON A.EMP_ID = C.EMP_ID 
where not exists(
   select 'next'
   from employee_master a2
   left outer join DESIGNATION_MAINTENANCE c2
     ON A2.EMP_ID = C2.EMP_ID 
   where a2.emp_id = a.emp_id
   and (c2.maint_id is null and c.maint_id is not null or 
   c2.maint_id > c.maint_id)
)

转到SQL Fiddle