要求是获取具有当前日期和上一个日期的客户销售记录。任何人都可以帮助我使用SQL获取数据。
下表是来源:
Name Order Sales date
Ann 1 13/01/2017
Ann 3 26/01/2017
Ann 6 14/03/2017
Ben 2 16/01/2017
Ben 5 21/02/2017
Cavin 4 15/03/2017
目标应为
Name Order latest_sales_date previous_sales_date
Ann 1 13/01/2017
Ann 3 26/01/2017 13/01/2017
Ann 6 14/03/2017 26/01/2017
Ben 2 16/01/2017
Ben 5 21/02/2017 16/01/2017
Cavin 4 15/03/2017
答案 0 :(得分:1)
使用ANSI标准lag()
功能:
select t.*,
lag(sales_date) over (partition by name order by sales_date) as prev_sales_date
from t;
答案 1 :(得分:1)
使用Oracle,Postgres或SQL Server 2012以后:
select t1.Name, t1.Order, t1.Sales_date as latest_sale,
lag(t1.Sales_Date) over (partition by t1.Name order by t1.Order) as previous_sales_date
from MyTable t1