SQL来填充缺少的几周的数据

时间:2018-11-22 12:13:02

标签: sql database

我想构建一个sql来填补缺少的几周数据。你能帮忙吗?

示例:

Year - Week    order
2018 W45        250
2018 W51        300

我希望显示如下:

Year - Week    order
2018 W45        250
2018 W46        250
2018 W47        250
2018 W48        250
2018 W49        250
2018 W50        250
2018 W51        300
...
2019 W52        300

假设日期限制为2019年12月。

谢谢

1 个答案:

答案 0 :(得分:0)

在PostgreSQL上,您可以尝试以下操作。

SELECT sq."year-week"
, sq.orders
FROM
(
SELECT LEFT(a.rstrt, 6) || W "year-week"
, a.orders
, ROW_NUMBER() OVER(PARTITION BY LEFT(a.rstrt, 6) || W ORDER BY a.rend DESC) RN 
FROM(SELECT "year-week" rstrt
, COALESCE(LEAD ("year-week", 1) OVER(), 2018 || ' W' || 52) rend
, orders
FROM orders
UNION 
SELECT '2019 W01', '2019 W52', 300) a
LEFT JOIN (SELECT generate_series(1, 52, 1) w) b ON b.w BETWEEN RIGHT(a.rstrt, 2)::INT AND RIGHT(a.rend, 2)::INT
ORDER BY LEFT(a.rstrt, 4)::INT, w
) sq
WHERE RN = 1;