首页 > 解决方案 > 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_highest_order_date_of_the_customer列。我可以使用窗口函数计算每个客户整体的第二高日期,但我很难在订单级别找到 second_highest_date,它不应该超过所述行中的 order_date。

非常感谢任何帮助

标签: sqldatatableaggregate-functionswindow-functionspresto

解决方案


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;

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


推荐阅读