任务如下: 我有交易记录,它们的特点是数量,交易时间,产品和数量。对于每笔交易,我需要查看时间,产品,交易量和此交易产品的最后N笔交易(在此交易前制作)的交易量。查询需要完成MS Access。数据如下所示:
Number | Time | Product | Volume
1 | 10 | A | 20
2 | 11 | B | 20
3 | 12 | B | 25
4 | 13 | A | 20
5 | 14 | A | 40
6 | 15 | B | 20
7 | 16 | C | 70
8 | 17 | A | 20
9 | 18 | B | 60
10 | 19 | B | 10
交易8和9的预期结果,前2名(N = 2):
Number | Time | Product | Volume | Sum
8 | 17 | A | 20 | 60
9 | 18 | B | 20 | 45
答案 0 :(得分:1)
这可以在MS Access中通过选择正确的行然后聚合来完成:
select max(t.number) as number, max(t.time) as time, t.product,
sum(volume)
from trades t
where t.time in (select top 5 t2.time
from trades as t2
where t2.product = t.product
order by t2.time desc
);
group by t.product;