SQL从子查询返回最大值

时间:2018-11-29 04:28:08

标签: sql sql-server

以下代码返回:

personID  lastname  firstname  number
-------------------------------------
  17520   doe       john       0192

代码:

select 
    personID, lastname, firstname, number
from 
    (select distinct
         max(sm.personID) as personID, 
         sm.lastName, 
         ISNULL(sm.alias, sm.firstName) as firstname,       
         max(sm.schoolNumber) as number, 
         max(assignmentID) as assignmentID
     from 
         staffmember sm
     where 
         (sm.endDate >= GetDate() or sm.endDate is null)
         and (sm.startDate <= GetDate())
     group by 
         sm.lastName, sm.firstName, sm.alias) as query
where 
    1 = 1

如果我拉出子查询并从schoolNumberassignmentID中删除最大聚合,然后将assignmentID添加到选择中,以使查询看起来像这样:

select distinct
max(sm.personID) as personID, 
sm.lastName, 
ISNULL(sm.alias, sm.firstName) as firstname,
sm.schoolNumber as number, 
sm.assignmentID as assignmentID
from staffmember sm
where (sm.endDate >= GetDate() or sm.endDate is null)
and (sm.startDate <= GetDate())
and personID = '17520'
group by sm.lastName, sm.firstName, sm.alias, sm.schoolNumber, sm.assignmentID

查询返回:

personID  lastname  firstname  number  assignmentID
----------------------------------------------------
17520     doe       john       0192    1354
17520     doe       john       0103    1538

我需要原始查询才能返回:

personID  lastname  firstname  number
-------------------------------------
17520     doe       john       0103

1 个答案:

答案 0 :(得分:1)

您可以在下面使用相关子查询尝试

select sm.personID as personID, sm.lastName, ISNULL(sm.alias, sm.firstName) as firstname,
sm.schoolNumber as number, 
sm.assignmentID as assignmentID
from staffmember sm
where (sm.endDate >= GetDate() or sm.endDate is null)
and (sm.startDate <= GetDate())
and personID = '17520' 
and assignmentID in 
    (select max(assignmentID) from staffmember sm1 where sm.personID =sm1.personid 
      and sm1.personID = '17520')