Select语句,但仅返回另一个联接表的最新项

时间:2018-11-05 13:30:28

标签: sql sql-server sql-server-2014

假设我正在选择候选人的详细信息及其工作经历。

Select candidate.id, candidate.firstname +' '+ candidate.lastname as 'Candidate Name', cwh.dateworked
from candidate
inner join canworkhistory cwh on candidate.id = cwh.candidateid

现在,候选人的工作日期有很多记录,但是我只想要最新的记录。

如何排序这些子项,以便在上面的查询中返回前1个?

5 个答案:

答案 0 :(得分:2)

您可以在外部应用最新行:

Select candidate.id, candidate.firstname +' '+ candidate.lastname as 'Candidate Name', cwh.dateworked
outer apply (select top 1 * from canworkhistory where candidate.id = canworkhistory.candidateid order by dateworked desc) cwh
from candidate

答案 1 :(得分:1)

您可以尝试使用窗口函数-row_number()

select * from
(
Select candidate.id, candidate.firstname +' '+ candidate.lastname as 'Candidate Name', cwh.dateworked,row_number() over(partition by candidate.id order by cwh.dateworked desc) as rn
from candidate inner join canworkhistory cwh 
on candidate.id = cwh.candidateid
)X where rn=1

答案 2 :(得分:1)

您可以将派生表与group bymax一起使用:

Select candidate.id, 
       candidate.firstname +' '+ candidate.lastname as 'Candidate Name', 
       cwh.dateworked
from candidate
inner join (
    select candidateid, max(dateworked) as dateworked
    from canworkhistory
    group by candidateid
) cwh on candidate.id = cwh.candidateid

答案 3 :(得分:1)

您可以尝试以下操作

 with cte as
   (
    Select candidate.id, candidate.firstname +' '+ candidate.lastname 
    as 'Candidate   Name', cwh.dateworked
    from candidate
    inner join canworkhistory cwh on candidate.id = cwh.candidateid
  ) select t.* from cte t where t.dateworked =
                ( select max(dateworked) from canworkhistory t1
                   where t1.candidateid=t.id
                     group by candidateid
                   )

答案 4 :(得分:1)

您也可以尝试使用CTE

;WITH RecentWork
     AS (SELECT
           candidateid
           ,max(dateworked)
         FROM
           canworkhistory
         GROUP  BY
          candidateid)
SELECT
  candidate.id
  ,candidate.firstname + ' ' + candidate.lastname AS 'Candidate Name'
  ,RecentWork.dateworked
FROM
  candidate
  INNER JOIN RecentWork
          ON candidate.id = RecentWork.candidateid