看起来您想选择四个最低的不同日期作为您的四次付款。我将介绍一种易于理解的方法来实现这一点:
- 查找付款1
- 再次加入表以查找 payment2
- 再次加入表以查找付款3
- ...
最终结果在这里:
with step1 as (
select id, min(date) as payment1
from ps
group by id
), step2 as (
select step1.*, min(date) as payment2
from step1
join ps on step1.id = ps.id
where step1.payment1 < ps.date
group by step1.id, payment1
), step3 as (
select step2.*, min(date) as payment3
from step2
join ps on step2.id = ps.id
where step2.payment2 < ps.date
group by step2.id, payment1, payment2
), step4 as (
select step3.*, min(date) as payment4
from step3
join ps on step3.id = ps.id
where step3.payment3 < ps.date
group by step3.id, payment1, payment2, payment3
)
select * from step4
这是一个展示它的小提琴:http://sqlfiddle.com/#!3/66576/8
现在这产生了 4 个连接,因此性能不是最好的。如果您在性能方面遇到问题,那么我会考虑对日期进行排名,选择四个最低的(不包括重复项),然后旋转表格。