[英]How to join with fill null by previous value
I have two tables that I want to join with filling null values by previous (closest by date).我有两个表,我想加入 null 值(按日期最近)填充。
CREATE TABLE a
( a_value int,
a_date DATE,
a_id int
);
CREATE TABLE b
( b_id int,
b_date DATE,
b_value float
);
INSERT INTO a VALUES (1, '20130603', 1);
INSERT INTO a VALUES (1, '20130704', 1);
INSERT INTO a VALUES (3, '20130805', 1);
INSERT INTO a VALUES (1, '20130906', 1);
INSERT INTO a VALUES (2, '20131007', 1);
INSERT INTO b VALUES (1, '20130603', 3.00);
INSERT INTO b VALUES (1, '20130706', 4.00);
INSERT INTO b VALUES (1, '20130906', 5.00);
I need to join like this, but I get null values in some a_dates.我需要像这样加入,但我在某些 a_dates 中得到了 null 个值。
SELECT a.a_value,
a.a_date,
a.a_id,
b.b_value,
b.b_date
FROM b
RIGHT JOIN a on a.a_id = b.b_id
AND b.b_date <= a.a_date
AND b.b_date >= timestampadd(day, -25, a.a_date)
ORDER BY a.a_date;
Result:结果:
a_value一个值 | a_date一个约会 | a_id援助 | b_value b_value | b_date b_date |
---|---|---|---|---|
1 1个 | 2013-06-03 2013-06-03 | 1 1个 | 3 3个 | 2013-06-03 2013-06-03 |
1 1个 | 2013-07-04 2013-07-04 | 1 1个 | (null) (无效的) | (null) (无效的) |
3 3个 | 2013-08-05 2013-08-05 | 1 1个 | (null) (无效的) | (null) (无效的) |
1 1个 | 2013-09-06 2013-09-06 | 1 1个 | 5 5个 | 2013-09-06 2013-09-06 |
2 2个 | 2013-10-07 2013-10-07 | 1 1个 | (null) (无效的) | (null) (无效的) |
But I would like to get with fill missing values by closest by date但我想按最接近的日期填充缺失值
a_value一个值 | a_date一个约会 | a_id援助 | b_value b_value | b_date b_date |
---|---|---|---|---|
1 1个 | 2013-06-03 2013-06-03 | 1 1个 | 3 3个 | 2013-06-03 2013-06-03 |
1 1个 | 2013-07-04 2013-07-04 | 1 1个 | 3 3个 | 2013-06-03 2013-06-03 |
3 3个 | 2013-08-05 2013-08-05 | 1 1个 | 4 4个 | 2013-07-06 2013-07-06 |
1 1个 | 2013-09-06 2013-09-06 | 1 1个 | 5 5个 | 2013-09-06 2013-09-06 |
2 2个 | 2013-10-07 2013-10-07 | 1 1个 | 5 5个 | 2013-09-06 2013-09-06 |
I tried to use coalesce:我尝试使用合并:
and coalesce(b.b_date,
(select b_date
from b as b1
where b1.b_date <a.a_date and b1.b_value is not null
order by b1.b_date desc
LIMIT 1)) <= a.a_date;
But get duplicates rows:(但是得到重复的行:(
How should I do it?我应该怎么做?
select a_value
,a_date
,a_id
,b_id
,b_date
,b_value
from
(
select *
,rank() over(partition by a_id, a_date, a_value order by datediff(a_date, b_date)) as rnk
from a full join b
where b_date <= a_date
) ab
where rnk = 1
a_value一个值 | a_date一个约会 | a_id援助 | b_id出价 | b_date b_date | b_value b_value |
---|---|---|---|---|---|
1 1个 | 2013-06-03 2013-06-03 | 1 1个 | 1 1个 | 2013-06-03 2013-06-03 | 3 3个 |
1 1个 | 2013-07-04 2013-07-04 | 1 1个 | 1 1个 | 2013-06-03 2013-06-03 | 3 3个 |
3 3个 | 2013-08-05 2013-08-05 | 1 1个 | 1 1个 | 2013-07-06 2013-07-06 | 4 4个 |
1 1个 | 2013-09-06 2013-09-06 | 1 1个 | 1 1个 | 2013-09-06 2013-09-06 | 5 5个 |
2 2个 | 2013-10-07 2013-10-07 | 1 1个 | 1 1个 | 2013-09-06 2013-09-06 | 5 5个 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.