You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Snowflake SQL中按分组去除首尾含NULL的行?

Snowflake SQL实现分组去除首尾空值行需求

需要按Account分组,剔除每组中首尾连续的Spend为null的行,但保留夹在有效数值之间的中间null行。

原始数据集

DateAccountSpend
1/2/21Anull
1/3/21Anull
1/4/21A4
1/5/21A6
1/6/21Anull
1/7/21A7
1/8/21Anull
1/2/21Bnull
1/3/21B4
1/4/21Bnull
1/5/21B7
1/6/21Bnull

目标结果数据集

DateAccountSpend
1/4/21A4
1/5/21A6
1/6/21Anull
1/7/21A7
1/3/21B4
1/4/21Bnull
1/5/21B7

实现SQL

WITH ranked_data AS (
    SELECT 
        Date,
        Account,
        Spend,
        ROW_NUMBER() OVER (PARTITION BY Account ORDER BY Date) AS row_num
    FROM your_table_name  -- 替换为你的实际表名
),
group_bounds AS (
    SELECT 
        Account,
        MIN(CASE WHEN Spend IS NOT NULL THEN row_num END) AS start_row,
        MAX(CASE WHEN Spend IS NOT NULL THEN row_num END) AS end_row
    FROM ranked_data
    GROUP BY Account
)
SELECT 
    rd.Date,
    rd.Account,
    rd.Spend
FROM ranked_data rd
JOIN group_bounds gb ON rd.Account = gb.Account
WHERE rd.row_num BETWEEN gb.start_row AND gb.end_row
ORDER BY rd.Account, rd.Date;

逻辑说明

  1. ranked_data CTE:按Account分组,给每组内的行按Date排序分配行号,确保数据顺序符合时间逻辑。
  2. group_bounds CTE:计算每个Account组内,第一个存在有效Spend值的行号(start_row)和最后一个存在有效Spend值的行号(end_row)。
  3. 最终筛选:关联两个CTE,只保留行号在start_row到end_row之间的行——这样自动剔除了每组开头和结尾的连续null行,而中间夹在有效数值之间的null行因处于有效范围被保留。

内容的提问来源于stack exchange,提问作者mdrishan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:45:29