[英]How to complete and fill in gaps between dates in SQL?
像这样的查询应该可以解决问题:
create table test (yq int, items int);
INSERT INTO test Values (20201,10),(20204, 15),(20213, 25),(20222, 30);
with recursive quarters(q) as (
select min(yq) as q
from test
union all
select decode(right(q::text, 1), 4, q + 7, q + 1) as q
from quarters
where q < (select max(yq) from test)
)
select q as yq, decode(items is null, true,
lag(items ignore nulls) over (order by q), items) as items
from test t
right join quarters q
on t.yq = q.q
order by q;
它使用递归 CTE 生成所需的季度范围,将其与源数据右连接,然后使用 LAG() window function 填充项目(如果值为 NULL)。
这被称为前向填充值:
CREATE TABLE #Temp
(
[YQ] nvarchar(5),
[items] int
)
INSERT INTO #Temp Values ('20201',10),('20204', 15),('20213', 25),('20222', 30)
---------------------------------------------------------------------------------
DECLARE @start int, @end int, @starty int, @endy int
SELECT @start=1, @end=4
SELECT @starty=MIN(Substring(YQ,0,5)), @endy=MIN(Substring(YQ,0,5)) from #Temp
;With cte1(y) as
(
Select @starty as y
union all
Select y + 1
from cte1
where y <= @endy + 1
)
, cte2(n) as
(
Select @start as n
union all
Select n + 1
from cte2
where n < @end
)
SELECT t1.YQ AS 'Year-Quarter',
CASE WHEN t2.items is null then (SELECT TOP 1 MAX(items) from #Temp WHERE items is not null and YQ < t1.YQ) ELSE t2.items END AS '# Items'
FROM
(
SELECT CAST(cte1.y AS nvarchar(4)) + CAST(cte2.n AS nvarchar(1)) AS YQ
FROM cte1, cte2
) t1
LEFT JOIN #Temp t2 ON t2.YQ = t1.YQ
WHERE t1.YQ <= (SELECT MAX(YQ) FROM #Temp)
ORDER BY t1.YQ, t2.items
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.