sql - 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。
非常感谢任何帮助
解决方案
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;
如果英语不是您的第一语言,倒数第二个是一个漂亮的词,意思是“序列中倒数第二个”。
推荐阅读
- python - 需要帮助使用带括号的字符串
- keycloak - 是否可以从 Keycloak 中检索 AUTH_SESSION_ID cookie?
- r - Anova 测试 - 具有两个因素比较的单独组
- ibm-cloud - 上传后 bluemix 应用程序推送挂起
- ios - 使用 PinLayout 制作网格视图
- python - 组合 2 个列表,每次 n 个元素
- swift - 在 Swift 中,为什么错误“类型别名引用自身”取决于类型别名的定义位置?
- excel - 插入的带有单元格引用的公式无法识别新输入
- html - 整个浏览器宽度上的 CSS 三角形
- typo3 - 创建自定义 TER (TYPO3) 服务器