我有一个查询,我想通过输入的最新日期和描述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
我确定它很简单,但我没有看到它。
答案 0 :(得分: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
答案 1 :(得分:0)
我没有看到加入[案例]表的原因,所以我把它留了出来。如果您出于某种原因需要,可以将其添加回来。
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行的评估,计划和案例表中有匹配的行,这将与您的查询略有不同。您可以通过为ARQ2添加联接来使其工作,但这会影响性能,也会更复杂一些。如果你需要,然后发表评论,我可以改变查询来处理它,或者你可以自己解决。
答案 2 :(得分:0)
简短回答:如果按ID分组,则max函数不起作用。您将最终返回每个不同ID的Max值。即一切
您可能需要更改子查询表示,但您明白了。
从表中选择id,val 其中val =(从表中选择max(val))