gpt4 book ai didi

SQL:从表中选择一行,其中包含该列的下一个值的附加列

转载 作者:行者123 更新时间:2023-12-04 15:12:43 24 4
gpt4 key购买 nike

假设我在 Oracle 数据库中有一个表“TABLE_A”:

=======================
| id | key | date |
=======================
| 0 | 1 | 1.1.2020 |
| 1 | 1 | 1.1.2021 |
=======================

我想得到这样的结果:

===================================
| id | key | date | next_date |
===================================
| 0 | 1 | 1.1.2020 | 1.1.2021 |
===================================

请注意,我想要带有特定键的行 <ID>在某个日期<DATE>与另一列包含数据库中具有相同键的下一个日期。但是,如果没有其他日期,它仍应给我同一行,但 next_date 为空。

有比这更简单/更好/更具可读性的版本吗?

SELECT a.*, next_date
FROM TABLE_A a,
(SELECT key, date as next_date
FROM TABLE_A
WHERE key = <ID>
AND date > <DATE>
AND ROWNUM <= 1
ORDER BY next_date asc) a2
WHERE key = <ID>
AND date = <DATE>
AND a2.key(+) = a.key

最佳答案

尽管 lead() 是您所描述的内容,但我认为相关子查询可能是最快的:

select t.*,
(select min(t2.date)
from t t2
where t2.key = t.key and t2.date > t.date
) as next_date
from t;

(您可以为特定键添加过滤器。)

特别是,这可以非常有效地使用 (key, date) 上的索引。

关于SQL:从表中选择一行,其中包含该列的下一个值的附加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64928075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com