繁体   English   中英

如何完成和填补 SQL 中日期之间的空白?

[英]How to complete and fill in gaps between dates in SQL?

我在 Redshift 中有数据,我正在汇总到年-季度级别,即按年-季度的项目数

我需要展示一个连续的趋势,因此我需要填补年度季度的空白。 下图应该可以更清楚地了解我当前的数据和所需的 output。

我怎样才能在 Redshift 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM