SQL窗口函数,用于查找每个客户在订单级别的第二高订单日期



我有一个包含以下字段的表:

| order_id  | order_date  | customer_id  | second_highest_order_date_of_the_customer
| 12345     | 2020-11-01  | customer_ABC | 2020-05-01
| 67891     | 2020-05-01  | customer_ABC | 2020-02-01
| 00531     | 2020-02-01  | customer_ABC | 2020-01-01
| 00789     | 2020-01-01  | customer_ABC | 

我发现在SQL中很难计算second_hight_order_date_of_the_customer列。我可以使用窗口函数计算每个客户的第二高日期,但我很难找到订单级别的第二个最高日期,该日期不应超过所述行中的order_date。

非常感谢任何帮助

nth_value()窗口函数可以执行您想要的操作:

select t.*,
nth_value(order_date, 2) over (partition by customer_id order by order_date desc) as penultimate_order_date
from t;

如果英语不是你的第一语言,倒数第二个是一个漂亮的词,意思是";序列中倒数第二个";。

最新更新