簡體   English   中英

使用 MySQL 或 H2 將 null 值替換為列中的最新值

[英]Replace null values with the latest value in a column using MySQL or H2

提出了相同的問題,但是提供的所有答案均適用於 SQL 服務器 2008,並且這兩種方法均不適用於 MySQL 或 H2:

用結果集系列中的最新非 NULL 值替換 NULL 值(SQL Server 2008 R2)

類似的問題(還有 SQL 服務器 2008,我們不知道所有表格)

用最新值替換 null 值

我需要的是可以與 MySQL 或 H2 一起使用的東西

所以如果我們有

product timestamp          price 
------- ----------------   -----
   5678 2008-01-01         12.34
   5678 2008-01-02         NULL
   5678 2008-01-03         NULL
   5678 2008-01-03         23.45
   5678 2008-01-04         NULL

結果應該是

product timestamp          price 
------- ----------------   -----
   5678 2008-01-01         12.34
   5678 2008-01-02         12.34
   5678 2008-01-03         12.34
   5678 2008-01-03         23.45
   5678 2008-01-04         23.45

MySQL 代碼:

CREATE TABLE `table1` (
  `product` int(11) NOT NULL,
  `timestamp` date NOT NULL,
  `price` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



INSERT INTO `table1` (`product`, `timestamp`, `price`) VALUES
(5678, '2008-01-01', '12'),
(5678, '2008-01-02', NULL),
(5678, '2008-01-03', NULL),
(5678, '2008-01-03', '23'),
(5678, '2008-01-04', NULL);

請保持簡單。

如果你有 mysql 6.x 你可以使用用戶定義的變量

CREATE TABLE table1 ( `product` INTEGER, `timestamp` DATETIME, `price` VARCHAR(5) ); INSERT INTO table1 (`product`, `timestamp`, `price`) VALUES ('5678', '2008-01-01 12:00', '12.34'), ('5678', '2008-01-01 12:01', NULL), ('5678', '2008-01-01 12:02', NULL), ('5678', '2008-01-01 12:03', '23.45'), ('5678', '2008-01-01 12:04', NULL);
 SELECT `product`, `timestamp`, @price:= IF(`price` IS NULL, @price,`price`) 'price' FROM (SELECT * FROM table1 ORDER BY `timestamp`) t1,(SELECT @price:= 0) t2
 產品 | 時間戳 | 價格 ------: |:----------------- |:---- 5678 |  2008-01-01 12:00:00 |  12.34 5678 |  2008-01-01 12:01:00 |  12.34 5678 |  2008-01-01 12:02:00 |  12.34 5678 |  2008-01-01 12:03:00 |  23.45 5678 |  2008-01-01 12:04:00 |  23.45

db<> 在這里擺弄

我把這個問題理解為更新表格數據,一個產品的價格不應該影響另一個產品的價格。 看起來像這樣:

set @price:=null, @product:=null;
update table1
    set price=if(price is not null,
        @price:=price,
        if(product=@product,@price,price)
    ),
    product=@product:=product
order by product, timestamp;

If the goal is just to replace null values with the previous value during select, this would be easily accomplished using window functions, except that neither mysql nor mariadb has yet implemented the LAG() IGNORE NULLS function:( so it requires use of variables (請參閱 nbk 的答案)或自加入:

select t.product, t.timestamp, coalesce(t.price, substr(max(concat(t2.timestamp,t2.price)),length(t.timestamp)+1)) price
from table1 t
left join table1 t2 on t2.product=t.product and t2.timestamp < t.timestamp and t.price is null and t2.price is not null
group by t.product, t.timestamp, t.price;

group by 是必需的,但會刪除重復的條目; 按主鍵分組會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM