Remou 提出了一个有效的观点,即唯一 ID 将是有益的,因为它将允许在未来引用第一行,但这可能是您无法控制的约束。
连字符年份的数据源有点尴尬,这会阻止简单的分组查询。第二个问题是,您不能只按TotalSpent
字段的最大值进行分组,因为它可能不是最后一个字段(例如,大笔退款可能会影响一年的总数)。
我的解决方案包括查找每个 ID 的最新年份(查询 A),然后修改年份标签以连接到表 B。我不想对计算字段执行连接,因此我将其包装在另一个子查询(查询乙)。然后将其连接到原始表/查询以提取关键行和值。
SELECT YourTable.[YourYearField],
YourTable.ID,
YourTable.TotalSpent
FROM (SELECT A.ID,
[StartYear] & "-" & [EndYear] AS Grouping
FROM (SELECT YourTable.ID,
Max(Val(Right$([YourYearField], 4))) AS EndYear,
Max(Val(Right$([YourYearField], 4)) - 1) AS StartYear
FROM YourTable
GROUP BY YourTable.ID) AS A
GROUP BY A.ID,
[StartYear] & "-" & [EndYear]) AS B
INNER JOIN YourTable
ON ( B.Grouping = YourTable.[YourYearField] )
AND ( B.ID = YourTable.ID )
GROUP BY YourTable.[YourYearField],
YourTable.ID,
YourTable.TotalSpent;