示例:
Table B Table A
ID Item Record ID Date
1 pen 10 1 1/1/2015
1 CD 40 2 7/3/2015
2 pen 20 3 5/8/2016
2 CD 50 4 10/12/2016
3 pen 8
3 CD 30
3 pen 5
4 pen 10
4 CD 35
结果如下:
ID Item Record LowestRecord Date
1 pen 10 10 1/1/2015
1 CD 40 40 1/1/2015
2 pen 20 10 7/3/2015
2 CD 50 40 7/3/2015
3 pen 8 5 5/8/2016
3 CD 30 30 5/8/2016
3 pen 5 5 5/8/2016
4 pen 10 5 10/12/2016
4 CD 35 30 10/12/2016
所以它选择最小值直到当前日期记录。 提前致谢。
答案 0 :(得分:1)
假设日期列是日期类型,您可以加入行表,如下所示:
select
a.*,
min(a.record) over (partition by item order by b.date, b.id) minrecord,
b.date
from tableA a
inner join tableB b
on a.id = b.id;
答案 1 :(得分:0)
您可以使用窗口功能,按项目对记录进行分组,并限制帧仅用于日期小于当前记录日期的记录,然后取最小值。
SELECT a.*
, min(a.record)
OVER (PARTITION BY Item ORDER BY b.[Date] DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS LowestRecord
, b.[DATE]
FROM
a JOIN b ON a.id = b.id