当数据集中缺少季度时如何使用上一季度的数据

问题描述 投票:0回答:1

我正在尝试在 Presto 中编写 SQL 查询来进行累积交付预测。然而,并不总是每个季度都有交付,因此对于没有交付的季度,该季度的数据根本没有行。发生这种情况时,我想使用上一季度的数据。

我尝试创建一个包含我想要填充的所有宿舍的 CTE,并使用一些窗口功能来填充缺失的数据。我试图对 if null, then LAG(quarter - 1) 使用 CASE 语句,但 CASE 语句一般似乎不起作用。

with forecasts as (
    select quarter, type, location, sum(total)
    from delivery_db
    group by 1,2,3
)

quarters AS (
    SELECT
        *
    FROM (
        VALUES
            ('2024-Q1'),
            ('2024-Q2'),
            ('2024-Q3'),
            ('2024-Q4')
    ) v(quarter)
)

SELECT
    q.quarter,
    f.type,
    f.location,
    --CASE(WHEN f.quarter is not null then SUM(total) else LAG(f.quarter, 1))
    SUM(total) OVER(
        PARTITION BY
            f.type
        ORDER BY
            q.quarter
    ) AS total
FROM quarters q
FULL JOIN forecasts f
on f.quarter = q.quarter

DeliveryDB 看起来像:

四分之一 类型 地点 总计
2024 年第一季度 A型 待定 10
2024 年第一季度 A型 待定 4
2024 年第 4 季度 A型 待定 5

实际

四分之一 类型 地点 总计
2024 年第一季度 A型 待定 14
2024 年第 2 季度
2024 年第三季度
2024 年第 4 季度 A型 待定 19

想要的

四分之一 类型 地点 总计
2024 年第一季度 A型 待定 14
2024 年第 2 季度 A型 待定 14
2024 年第三季度 A型 待定 14
2024 年第 4 季度 A型 待定 19
sql presto
1个回答
0
投票

参见示例

with forecasts as (
  select quarter, type, location, sum(total) total
    from delivery_db
    group by quarter, type, location
)
,quarters AS (
    SELECT *
    FROM (
        VALUES
            ('2024-Q1'),
            ('2024-Q2'),
            ('2024-Q3'),
            ('2024-Q4')
    ) v(quarter)
)
,AllPoints as(
   select * 
   from quarters,
    (select distinct type,location from forecasts)f
)
SELECT
    q.quarter,
    q.type,
    q.location,
    SUM(case when f.quarter=q.quarter then total else 0 end) 
       OVER(PARTITION BY q.type,q.location ORDER BY q.quarter
     ) AS total2,
     f.quarter,
     f.total qtl_total
FROM AllPoints q
left join forecasts f on q.quarter= f.quarter
    and q.type=f.type and q.location=f.location
order by type,location,q.quarter

输出

季度 类型 地点 总计 四分之一 qtl_total
2024 年第一季度 A型 待定 14 2024 年第一季度 14
2024 年第 2 季度 A型 待定 14
2024 年第三季度 A型 待定 14
2024 年第 4 季度 A型 待定 19 2024 年第 4 季度 5
2024 年第一季度 B型 待定 7 2024 年第一季度 7
2024 年第 2 季度 B型 待定 7
2024 年第三季度 B型 待定 15 2024 年第三季度 8
2024 年第 4 季度 B型 待定 15
2024 年第一季度 B型 待定 0
2024 年第 2 季度 B型 待定 0
2024 年第三季度 B型 待定 3 2024 年第三季度 3
2024 年第 4 季度 B型 待定 3
2024 年第一季度 B型 TBX 33 2024 年第一季度 33
2024 年第 2 季度 B型 TBX 33
2024 年第三季度 B型 TBX 33
2024 年第 4 季度 B型 TBX 33
2024 年第一季度 B型 待定 0
2024 年第 2 季度 B型 待定 0
2024 年第三季度 B型 待定 0
2024 年第 4 季度 B型 待定 51 2024 年第 4 季度 51
© www.soinside.com 2019 - 2024. All rights reserved.