我有一個看起來像這樣的表:
| ID | 掙錢 | days_since_start |
|---|---|---|
| 1 | 1000 | 1 |
| 1 | 2000 | 2 |
| 1 | 空值 | 3 |
| 1 | 3000 | 4 |
| 1 | 2000 | 5 |
| 2 | 1000 | 1 |
| 2 | 空值 | 2 |
| 2 | 100 | 3 |
我想要那些在 money_earned 中沒有值的行(這意味著那一天 money_earned 列是空的) - 將用最后一個已知值填充 money_earned,所以它看起來像這樣:
| ID | 掙錢 | days_since_start |
|---|---|---|
| 1 | 1000 | 1 |
| 1 | 2000 | 2 |
| 1 | 2000 | 3 |
| 1 | 3000 | 4 |
| 1 | 2000 | 5 |
| 2 | 1000 | 1 |
| 2 | 1000 | 2 |
| 2 | 100 | 3 |
我試圖尋找類似的東西,但 postgresql 不支持在滯后視窗函式中忽略空值:(
謝謝你!
uj5u.com熱心網友回復:
LOG() 函式將適合此目的,但在您的情況下,您需要首先獲取不為空的前一個元素。LOG() 函式無法處理的內容。
我建議創建您自己的函式,該函式將回傳前一個元素的第一個非空值。
CREATE OR REPLACE FUNCTION log_not_null(row_num int, dafult text = '1001') RETURNS text LANGUAGE plpgsql AS $$
DECLARE
result text;
index int;
BEGIN
if row_num > 0 then
index := row_num - 1;
else
return dafult;
end if;
result := (select money_earned from my_table offset index limit 1);
if result is null then
return log_not_null(index);
end if;
return result;
END
$$;
select id, log_not_null((row_number() over ())::int) as money_earned, days_since_start from my_table;
筆記:
如果前一個值為 null,則遞回呼叫該函式,直到到達頂部元素,如果頂部元素也為 null,則該函式將從 dafult 變數回傳值。
DBfiddle中的演示
uj5u.com熱心網友回復:
你可以這樣做(警告,未經測驗!??):
UPDATE yourtable t1
SET money_earned = t3.money_earned
FROM yourtable
LEFT JOIN (SELECT
ID,
MAX(days_since_start) m
FROM yourtable
WHERE ID=t1.ID AND days_since_start<t1.ID) t2 ON t2.ID=i1.ID
INNER JOIN yourtable t3 ON t3.ID=t1.ID and t3.days_since_start = t2.days_since_start
WHERE t1.money_earned is null
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/468317.html
標籤:sql PostgreSQL
