【问题标题】:how to select third, fourth, fifth date in sql using window function如何使用窗口函数在sql中选择第三、第四、第五个日期
【发布时间】:2021-06-01 06:17:12
【问题描述】:

电影的表租借有这个数据:

  rental_id rental_ts   inventory_id    customer_id return_ts
  11909     2/14/2020     871           474         3/15/2020
  12222     2/14/2020     3949          22          4/18/2020

如何生成对:

第一次出租_ts,第二次出租日期,

第二次出租,第三次出租日期, ....

第二个 LAST 租借日期,最后租借日期,

最后租赁日期,null?

使用窗口函数 - 这不起作用:

select 
customer_id,
rental_ts as first_rental_date , 
lead(rental_ts) over(partition by customer_id order by rental_ts) as second_rental_date,
lead(lead(rental_ts) over(partition by customer_id order by rental_ts)) as third_rental_date

from rental 

我希望:

customer_id , rental_date, second_rental_date, third_rental_date ... second_last_rental_date, last_rental_date

1            2/14/2020       1/14/2020      12/13/2019    12/13/2019
2            5/16/2020       5/13/2020      5/07/2020     4/29/2020

基本上我需要多于 1 级回退 - 但不知道如何使用它,我在工作中只使用 1 个lead() 或 lag() 来比较当前和以前的日期

【问题讨论】:

  • 编辑您的问题并显示您想要的结果。
  • @GordonLinoff ,完成,先生,希望现在清楚

标签: sql sql-server window-functions lag lead


【解决方案1】:

您不需要使用动态枢轴吗?但如果你想要这样的话,你可以使用lead(rental_ts,2)、lead(rental_ts,3)等...

 select 
customer_id,
rental_ts as first_rental_date , 
lead(rental_ts) over(partition by customer_id order by rental_ts) as second_rental_date,
lead(rental_ts,2) over(partition by customer_id order by rental_ts) as third_rental_date

from rental 

【讨论】:

  • 很好,但我要补充一点,因为您的列使用相同的窗口。您可以定义和重用window-alias。
猜你喜欢
  • 2014-07-23
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2017-11-23
  • 2016-12-30
  • 2015-04-11
  • 1970-01-01
  • 2016-10-07
相关资源
最近更新 更多