嵌套LEFT JOIN语句

时间:2017-09-29 15:13:40

标签: sql sql-server nested left-join

目前,这两个LEFT JOINS分别返回最大CaseloadID和ClientQuestionnaireDate。我希望能够基于max ClientQuestionnaireDate返回CaseloadID,以便它返回最新的CaseloadID而不是最大的CaseloadID。

这应该可以通过在ClientQuestionnaireDate查询中嵌套CaseloadID查询来实现,但我不确定如何执行此操作。

LEFT JOIN 
    (SELECT ClientID, MAX(CaseloadID) [LastAssCase]
     FROM tblClientQuestionnaire
     WHERE QuestionnaireID = 10
     GROUP BY ClientID) AssessmentCaseload ON AssessmentCaseload.ClientID = c.ClientID
LEFT JOIN 
    (SELECT ClientID, MAX(ClientQuestionnaireDate) [LastAssDate]
     FROM tblClientQuestionnaire
     WHERE QuestionnaireID = 10
     GROUP BY ClientID) LastAssessment ON LastAssessment.ClientID = c.ClientID

任何有关如何实现这一目标的帮助将不胜感激。

下面列出了相关的表格和列:

  • tblClientQuestionnaire - ClientID,ClientQuestionnaireDate,QuestionnaireID

  • tblClientActivity - ClientID,ClientQuestionnaireDate

  • tblCaseload - CaseloadID,CaseloadName

3 个答案:

答案 0 :(得分:0)

如果我们假设:

  • tblCaseLoad有一个clientID和questionniareID

然而,这似乎很奇怪,因为如果有多个问卷,则重复案件。如果没有重复。然后由客户选择最大问卷将给我们最大的情况。因为案件只能有1份问卷。

我们可以:

  • 使用外部申请Top1获取每个客户的最新调查问卷日期
  • 使用左连接到tblCaseLoad来获取与每个客户的最新调查问卷日期相关的案例详细信息

也许这是可疑的:

SELECT *
FROM tblClientActivity CA
OUTER APPLY (SELECT TOP 1 * 
             FROM tblClientQuestionnaire 
             WHERE CA.ClientID = CQ.ClientID 
               AND CA.ClientQuestionnaireDate = CA.ClientQuestionnaireDate
             ORDER BY CA.ClientQuestionnaireDate Desc) CQ2
LEFT JOIN tblCaseLoad CL
  on CQ2.Client = CL.ClientID
 and CQ2.QuestionnaireID = CL.QuestionnaireID 

或许这个(更有可能):

SELECT * 
FROM tblClientActivity CA
OUTER APPLY (SELECT TOP 1 * 
             FROM tblClientQuestionnaire 
             WHERE CA.ClientID = CQ.ClientID 
             ORDER BY ORDER BY ClientQuestionnaireDate DESC) CQ
LEFT JOIN tblCaseLoad
  on CQ.ClientID = CL.ClientID
 and CQ.QuestionnaireID = CL.QuestionnaireID

这两个都是基于许多假设的猜测,因为问题中提供的信息缺乏足够的细节来理解问题并设计解决方案。

答案 1 :(得分:0)

尝试使用窗口功能。这假设CaseLoadID也在tblClentActivity中。

SELECT distinct tcq.ClientID, FirstValue(tca.CaseloadID) Over (Partition By tcq.ClientID Order by tcq.ClientQuestionnaireDate Desc)
FROM tblClientQuestionnaire tcq
INNER JOIN tblClentActivity tca on tca.ClientID = tcq.ClientID

答案 2 :(得分:0)

对LastAssessment查询使用公用表表达式(CTE),而不是使用子查询。像这样:

WITH LastAssessment as (
SELECT ClientID, 
    MAX(ClientQuestionnaireDate) [LastAssDate]
FROM tblClientQuestionnaire
WHERE QuestionnaireID = 10
GROUP BY ClientID
)
<... your query here ...>
LEFT JOIN (SELECT ClientID, CaseloadID [LastAssCase]                                               
        FROM tblClientQuestionnaire cq
        INNER JOIN LastAssessment la
            ON cq.ClientId = la.ClientId
            AND cq.ClientQuestionnaireDate = la.LastAssDate
        WHERE QuestionnaireID = 10
        GROUP BY ClientID ) AssessmentCaseload ON AssessmentCaseload.ClientID = c.ClientID
LEFT JOIN LastAssessment la
    ON la.ClientID = c.ClientID