我想查询一个表并返回与每个外键实例关联的最新日期。例如:
换句话说,我希望我开始使用ExpenditureDate
中具有最高价值的每个项目的支出,使用以下查询来获取最后一次支出,但这是错误的,因为添加的最后一个不是永远是最新的日期:
WITH LatestCumulativeExpenditure AS
(
SELECT DISTINCT
MAX(p.Id) AS Id
FROM
tbl_ProjectExpenditure p
GROUP BY
p.ProjectID
)
SELECT
pe.Id,
pe.ProjectID,
pe.CumulativeMonthlyExpenditure
FROM
tbl_ProjectExpenditure pe
INNER JOIN LatestCumulativeExpenditure lce
ON pe.Id = lce.Id
INNER JOIN tbl_Project p
ON pe.ProjectID = p.Id
答案 0 :(得分:1)
而不是查询MAX(p.Id)
,而是查询MAX(ExpenditureDate)
。您还需要其他列,例如ProjectID
,并加入两列。
WITH LatestCumulativeExpenditure AS
(
SELECT DISTINCT
-- Get both the ProjectID and the max ExpenditureDate
ProjectID,
MAX(ExpenditureDate) AS maxdate
FROM
tbl_ProjectExpenditure
GROUP BY
ProjectID
)
SELECT
pe.Id,
pe.ProjectID,
pe.CumulativeMonthlyExpenditure
FROM
tbl_ProjectExpenditure pe
INNER JOIN tbl_Project p
ON pe.ProjectID = p.Id
-- Join *both* columns against the primary tbl_ProjectExpenditure
-- to match the row with that expenditure date per project Id
INNER JOIN LatestCumulativeExpenditure lce
ON pe.ProjectID = lce.ProjectID
AND pe.ExpenditureDate = lce.maxdate
(编辑 - 抱歉,顶部说明中的列名错误)
答案 1 :(得分:1)
以下内容如何:
SELECT p.Id, p.ProjectID,
(
SELECT CumulativeMonthlyExpenditure
FROM tbl_ProjectExpenditure pe
WHERE pe.ProjectID = p.Id
ORDER BY ExpenditureDate DESC
LIMIT 1
) AS MAX_CumulativeMonthlyExpenditure
FROM tbl_Project p