2017-01-23 115 views
0

我有两个表:Candidate:{IdName}和Candidate_Education:{IdCandidateIdEducationGraduationDate}在右表上加入两个特殊情况的表格?

我想说明的候选人的名字和他过去的教育,我做了查询:

SELECT c.Name, ce.Education AS 'Last Education' 
FROM Candidate c 
LEFT JOIN Candidate_Education ce 
    ON c.Id = (SELECT TOP 1 CandidateID FROM Candidate_Education 
       ORDER BY GraduationDate DESC) 

但结果不正确,还有谁赋予的教育考生,他们没有与Candidate_Education关系

回答

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的替代方案。

+0

什么是'ce。 *'?它只是'*'? –

+0

@MohamedAhmed。 。 。我喜欢在任何地方使用列名。因此'ce。*'。 –

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 
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和日期数据类型