1

我有一个查询,我想通过输入的最新日期和描述 ID 获得不同的描述。我可以得到不同的部分,但我在尝试获取 ID 时遇到了麻烦,因为我在日期使用 MAX。这是查询:

SELECT DISTINCT Resource.Description, MAX(arq.DateReferred) AS DateReferred, arq.AssessmentResourceID
FROM AssessmentXResource AS arq 
INNER JOIN Resource ON arq.ResourceID = Resource.ResourceID 
INNER JOIN Assessment AS aq 
INNER JOIN [Case] AS cq ON aq.CaseID = cq.CaseID 
INNER JOIN [Plan] AS pq ON cq.CaseID = pq.CaseID ON arq.AssessmentID = aq.AssessmentID
WHERE     (pq.PlanID = 22)
GROUP BY Resource.Description, arq.AssessmentResourceID
ORDER BY Resource.Description

我确定它很简单,但我没有看到它。

4

3 回答 3

1
SELECT
    Resource.Description,
    arq.DateReferred AS DateReferred,
    arq.AssessmentResourceID
FROM
    Resource
INNER JOIN
    AssessmentXResource AS arq 
        ON arq.ResourceID = Resource.ResourceID 
        AND arq.DateReferred = (
                                SELECT
                                    MAX(DateReferred)
                                FROM
                                    AssessmentXResource
                                WHERE
                                    ResourceID = Resource.ResourceID
                               )
INNER JOIN
    Assessment AS aq
        ON arq.AssessmentID = aq.AssessmentID
INNER JOIN
    [Case] AS cq
        ON aq.CaseID = cq.CaseID 
INNER JOIN
    [Plan] AS pq
        ON cq.CaseID = pq.CaseID
WHERE
    (pq.PlanID = 22)
ORDER BY
    Resource.Description
于 2009-02-03T19:04:05.420 回答
0

我看不出加入 [Case] 表的原因,所以我把它省略了。如果出于某种原因需要它,您可以将其添加回来。

SELECT
     RES.Description,
     ARQ.DateReferred,
     ARQ.AssessmentResourceID
FROM
     AssessmentXResource ARQ
INNER JOIN Resource ON
     ARQ.ResourceID = RES.ResourceID
INNER JOIN Assessment AQ ON
     AQ.AssessmentID = ARQ.AssessmentID
INNER JOIN [Plan] PQ ON
     PQ.CaseID = AQ.CaseID
LEFT OUTER JOIN AssessmentXResource ARQ2 ON
     ARQ2.ResourceID = ARQ.ResourceID AND
     ARQ2.DateReferred > ARQ.DateReferred
WHERE
     PQ.PlanID = 22 AND
     ARQ2.ResourceID IS NULL

如果您的数据中相同的 ResourceID 存在相同的 DateReferred 值,则这可能不会起到预期的作用。您应该针对这种情况提出一个业务规则并相应地更改查询。此外,如果不能保证您的 AssessmentXResource 行的 Assessment、Plan 和 Case 表中有匹配的行,这将与您的查询略有不同。您可以通过为那些添加到 ARQ2 的连接来使其工作,但这会影响性能并且也更复杂一些。如果您需要,请发表评论,我可以更改查询以处理它,或者您可以自己解决。

于 2009-02-03T18:56:21.957 回答
0

简短回答:如果您按 id 分组,max 函数将不起作用。您最终将返回每个不同 id 的最大值。即一切

您可能需要更改子查询表示,但您明白了。

select id, val from table where val = (select max(val) from table)

于 2009-02-03T19:12:23.483 回答