简体   繁体   English

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

[英]Select statement but only return the most recent item of another joined table

Let's say I'm selecting a candidates details and their work history. 假设我要选择候选人的详细信息及其工作经历。

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

Now there's multiple records for the dates the candidate has worked but I only want the most recent one. 现在,有关于候选人工作日期的多个记录,但是我只想要最新的记录。

How do I order these sub-items so that the top 1 is returned in the above query? 如何排序这些子项,以便在上面的查询中返回前1个?

You can OUTER APPLY the latest row: 您可以在外部应用最新行:

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

You can try using window function - row_number() 您可以尝试使用窗口函数-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

You can use a derived table with group by and max : 您可以将派生表与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

you can try like below 你可以尝试如下

 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
                   )

You can try using a CTE as well 您也可以尝试使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM