![](/img/trans.png)
[英]Could you figure out why my code isn't working when it was working previously?
[英]Why isn't my code to select the latest non null value for a column and fill in the nulls not working?
我有一個表 T1,其中包含產品及其狀態的每日快照:
快照日期 | 產品編號 | 地位 |
---|---|---|
2022-01-03 | 1個 | 賣 |
2022-01-02 | 1個 | 待辦的 |
2022-01-01 | 1個 | 有存貨 |
2022-01-03 | 2個 | Null |
2022-01-02 | 2個 | Null |
2022-01-01 | 2個 | 賣 |
2022-01-03 | 3個 | Null |
2022-01-02 | 3個 | Null |
2022-01-01 | 3個 | 待辦的 |
我想編寫代碼來檢測每個產品的最新狀態並為每一行填充它,如果它是 null 它將 select 不是 null 的最新選項。最終的 output 應該是:
快照日期 | 產品編號 | 地位 |
---|---|---|
2022-01-03 | 1個 | 賣 |
2022-01-02 | 1個 | 賣 |
2022-01-01 | 1個 | 賣 |
2022-01-03 | 2個 | 賣 |
2022-01-02 | 2個 | 賣 |
2022-01-01 | 2個 | 賣 |
2022-01-03 | 3個 | 待辦的 |
2022-01-02 | 3個 | 待辦的 |
2022-01-01 | 3個 | 待辦的 |
我寫了這段代碼,但由於某種原因它不起作用,有人知道為什么以及如何修復它嗎?
SELECT
SnapshotDate,
ProductId,
COALESCE(Status,
LAG(Status) OVER (PARTITION BY ProductId ORDER BY SnapshotDate DESC)
) AS Status
FROM
T1
我也試過 Lead,但也不管用
嘗試使用LAST_VALUE
+ IGNORE NULLS
NULLS 修飾符,而不是LAG
。
SELECT SnapshotDate,
ProductId,
COALESCE(Status,
LAST_VALUE(Status IGNORE NULLS) OVER (
PARTITION BY ProductId
ORDER BY SnapshotDate
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
) AS Status
FROM T1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.