[英]Get Last Value from Previous Window Partition in Teradata SQL
[英]Get Last Value of previous row partition in SQL
在我的數據集中,每個客戶在不同日期都有一些訂單。 對於每個月的每個客戶,我想查看他/她上個月在哪個城市的最后一個訂單。
例如,這是我的一位客戶的數據。
顧客 | 年 | 月 | 天 | 訂單編號 | 城市編號 |
---|---|---|---|---|---|
1544 | 2022年 | 2個 | 6個 | 413 | 9 |
1544 | 2022年 | 2個 | 17 | 39 | 10 |
1544 | 2022年 | 3個 | 5個 | 115 | 21 |
1544 | 2022年 | 5個 | 29 | 2153 | 4個 |
1544 | 2022年 | 5個 | 30 | 955 | 9 |
結果應與此相同:
顧客 | 年 | 月 | 上個月最后訂單城市(prevCity) |
---|---|---|---|
1544 | 2022年 | 2個 | null 或 9 |
1544 | 2022年 | 3個 | 10 |
1544 | 2022年 | 5個 | 21 |
(上表的第一行現在不是我的問題。)我使用last_value
編寫查詢,與此相同:
select customer,
year,
month,
last_value(City) over (partition by customer, year, month order by created_at desc
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) as prevCity
from table1
但結果是假的!
我該如何糾正這個問題?
與WITH TIES
子句一起使用 window function lag() over()
Select top 1 with ties
customer
,year
,month
,LastCityID = lag([city id],1) over (partition by customer order by year, month,day)
From YourTable
order by row_number() over (partition by customer,year,month order by year, month,day)
或者推動更多性能
with cte as (
Select *
,LastCityID = lag([city id],1) over (partition by customer order by year, month,day)
,RN = row_number() over (partition by customer,year,month order by year, month,day)
From YourTable
)
Select customer
,year
,month
,LastCityID
From cte
Where RN =1
結果
customer year month LastCityID
1544 2022 2 NULL
1544 2022 3 10
1544 2022 5 21
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.