在右边的桌子上加入两张带特殊情况的桌子?

时间:2017-01-23 12:31:15

标签: sql sql-server tsql

我有两张表:Candidate:{IdName}和Candidate_Education:{IdCandidateId,{{1 },Education}

我想要显示候选人姓名和他最后的教育,我提出了这个问题:

GraduationDate

但结果不正确,有候选人指定他们与Candidate_Education无关的教育

3 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER()OUTER APPLY

执行所需操作的更常用方法
SELECT c.Name, ce.Education
FROM Candidate c OUTER APPLY
     (SELECT TOP 1 ce.*
      FROM Candidate_Education ce
      WHERE ce.CandidateID = c.CandidateID
      ORDER BY ce.GraduationDate DESC
     ) ce;

您的查询缺少FROM子句中两个表之间的连接条件。但是,有一些替代方案更适合SQL Server。

答案 1 :(得分:0)

其他解决方案

with OneCandidate as (
select * from (
                select ce.*, ROW_NUMBER() over(partition by  ce.CandidateID order by ce.CandidateID desc) rang 
                from Candidate_Education ce
                ) tmp 
where tmp.rang=1
)
SELECT c.Name, ce.Education
FROM Candidate c left outer OneCandidate ce on ce.CandidateID = c.CandidateID

答案 2 :(得分:0)

WITH maxGraduationCTE AS
(SELECT Id, MAX(GraduationDate) AS 'Last Education' FROM Candidate_Education 
 GROUP BY Id),

lastEducationCTE AS 
(SELECT [Last Education], ce.Id, ce.CandidateId, ce.Education FROM maxGraduationCTE
 INNER JOIN Candidate_Education ce ON maxGraduationCTE.Id = ce.Id);

SELECT c.Name, 
CASE WHEN [Last Education] IS NULL THEN 'No Education'
     ELSE CAST([Last Education] As Varchar) 
END As [Last Education]
FROM Candidate c
LEFT JOIN lastEducationCTE ce
ON c.Id = ce.CandidateId

您可以使用两个CTE表达式和一个带CASE语句的左连接来处理空值。我使用了一个案例因为我不确定GraduationDate的数据类型...可能要转换它因为如果它是一个日期,你不能混合varchar和日期数据类型