需要帮助编写查询(LEFT JOIN)

时间:2016-04-20 13:55:14

标签: sql

有研究提案。决定是在提案上做出的。决定只能有4种类型。我需要显示与某位研究人员相关的所有已审核提案的最新决策。这就是我到目前为止所做的:

SELECT p.ProposalID
    ,p.Title
    ,p.DATE
    ,p.Submitted
    ,p.ReviewCompleted
    ,d.DecisionID
    ,dt.Description AS Decision
FROM Proposal p
LEFT JOIN (
    SELECT TOP 1 *
    FROM Decision
    ORDER BY DATE
    ) d
    ON d.ProposalID = p.ProposalID
LEFT JOIN DecisionType dt
    ON dt.DecisionTypeID = d.DecisionTypeID
WHERE p.ReviewCompleted = '1'
    AND p.ProposalID IN (
        SELECT ProposalID
        FROM Proposal
        WHERE ResearcherID = ?
        )
ORDER BY d.DATE

据我所知,这个问题来自第一次左连接,但我无法弄清楚如何获得关于p.ProposalID的最新决定。非常感谢你。

2 个答案:

答案 0 :(得分:1)

您似乎使用MSSQL(如果是这样,请将其添加到标记中)。在这种情况下,使用ROW_NUMBER() function

重写此LEFT JOIN
LEFT JOIN (
    SELECT TOP 1 *
    FROM Decision
    ORDER BY DATE
    ) d
    ON d.ProposalID = p.ProposalID

LEFT JOIN (
    SELECT Decision.*, 
    ROW_NUMBER() OVER(PARTITION BY ProposalID ORDER BY DATE DESC) AS Row_num
    FROM Decision
    ) d
    ON (d.ProposalID = p.ProposalID)
       AND (Row_num = 1)

在这里,您需要计算每个组的行号并按日期排序。然后,仅为每个组选择第一个(Row_num = 1)。

答案 1 :(得分:1)

您也可以使用OUTER APPLY编写此查询:

FROM Proposal p OUTER APPLY
     (SELECT TOP 1 *
      FROM Decision d
      WHERE d.ProposalID = p.ProposalID
      ORDER BY DATE DESC
     ) d LEFT JOIN
     DecisionType dt
     ON dt.DecisionTypeID = d.DecisionTypeID

OUTER APPLY是SQL Server对"横向连接"的实现。有时,使用APPLY的查询具有性能优势。