我有一张表格,对于每个项目,可以为每个国家/地区设置不同的预算。该表仅在更改时存储预算 - 因此,如果缺少月份,则表示预算保持不变。我正在尝试使用上个月的预算(在同一country_code组内)填充缺失值,以便我可以查看每个月的item-country_code预算。
我已经完成了我的查询以获得2个如下所示的表(如果下面设置的表格不起作用,我会道歉 - 我通过许多查询和其他表的子查询得到这些表)。注意:表b只是我用所有年份和月份构建的日历表。 table g是我试图转换的表,并填充值以获取最终的输出表。也许表b甚至不需要......
CREATE TABLE b
(date_ym INT PRIMARY KEY NULL
);
CREATE TABLE g
(item_number INT NULL,
country_code CHAR(2) NULL,
budget INT NULL,
budget_set_date INT NULL,
earliest_budget_set_date INT NULL
);
INSERT INTO b VALUES
(201706),
(201607),
(201608),
(201609);
INSERT INTO g VALUES
(1, 'AU', 100, 201606, 201606),
(1, 'AU',NULL, 201609, 201606),
(1, 'US' NULL, 201606, 201606),
(1, 'US', 200, 201607, 201606),
(1, 'US', 100, 201608, 201606),
(1, 'DE', 50 , 201609, 201609),
(2, 'AU' NULL, 201608, 201608),
(2, 'DE', 200, 201606, 201606),
(2, 'DE', NULL, 201608, 201606);
连接的最终输出应如下所示:
item_number | country_code | budget | date_ym
1 | AU | 100 | 201606
1 | AU | 100 | 201607
1 | AU | 100 | 201608
1 | AU | NULL | 201609
1 | US | NULL | 201606
1 | US | 200 | 201607
1 | US | 100 | 201608
1 | US | 100 | 201609
1 | DE | 50 | 201609
2 | AU | NULL | 201608
2 | AU | NULL | 201609
2 | DE | 200 | 201606
2 | DE | 200 | 201607
2 | DE | NULL | 201608
2 | DE | NULL | 201609
我尝试了很多东西,但无法得到正确的答案 - 将日历表交叉加入我的表格,以获取b.date_ym> = g.earliest_budget_set_date但不是&#的所有值39;工作。并且还使用变量来捕获上一个预算集以提前到下一行。
答案 0 :(得分:1)
如果我理解正确,你可以使用cross join
生成行,然后子查询引入值。
我有点不清楚日期比较的确切逻辑是什么,但这个想法是这样的:
select ic.item-number, ic.country_code, b.date_ym,
(select g.budget
from g
where g.item_number = ic.item_number and
g.country_code = ic.country_code and
g.budget_set_date >= b.date_ym
order by b.date_ym
limit 1
) as budget
from (select distinct item_number, country_code from g) ic cross join
b ;