我有两个表,都有一个公共ID列。第二个表包含与第一个表中的ID列匹配的多个行,我需要从第二个表返回最新的条目。我的解决方案几乎是正确的,但它在所有ID列中返回单个值,而不是与该实际ID列对应的值。
正如您所看到的,它正在处理付款,因此只需要返回最近付款所涵盖的日期。
(SELECT TOP 1CONVERT(VARCHAR,MemberPayments.CoverFinishDay,105)
FROM
Members LEFT JOIN MemberPayments
ON Members.MemberID = MemberPayments.MemberID
AND MemberPayments.CoverFinishDay = (
SELECT MAX(CoverFinishDay)
FROM MemberPayments
WHERE Members.MemberID = MemberPayments.MemberID
))
任何想法为什么它会在所有人中返回一个值?
答案 0 :(得分:1)
这是你在找什么?
;WITH LatestMemPayments AS
(
SELECT MemberID
,CoverFinishDay = MAX(CoverFinishDay)
FROM MemberPayments
GROUP BY MemberID
)
SELECT *
FROM Members ME
JOIN LatestMemPayments MP ON ME.MemberID = MP.MemberID
写为派生表而不是CTE;
SELECT *
FROM Members ME
JOIN (
SELECT MemberID
,CoverFinishDay = MAX(CoverFinishDay)
FROM MemberPayments
GROUP BY MemberID
) MP ON ME.MemberID = MP.MemberID
可能是单个查询;
SELECT ME.Col1
,ME.Col2
,CoverFinishDay = MAX(MP.CoverFinishDay)
FROM Members ME
JOIN MemberPayments MP ON ME.MemberID = MP.MemberID
GROUP BY ME.Col1
,ME.Col2
答案 1 :(得分:0)
试试这个,它会在MemberPayments中找到最新数据的所有信息:
SELECT *
FROM
Members
OUTER APPLY
(SELECT top 1 *
FROM
MemberPayments
WHERE
Members.MemberID = MemberPayments.MemberID
ORDER BY
CoverFinishDay DESC) x
如果您只需要最新日期:
SELECT m.MemberID, m.Field2, m.Field3, max(mp.CoverFinishDay) as LatestDate
FROM
Members m
LEFT JOIN
MemberPayments mp
ON
Members.MemberID = MemberPayments.MemberID
GROUP BY m.MemberID, m.Field2, m.Field3