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

如何根据Status列的多组合条件在SQL中筛选指定行数据?

按Status优先级筛选表数据的SQL实现

需求说明

针对包含Id和Status两列的表,需按以下规则筛选数据:

  • 若同一Id组内同时存在Success和Pending状态,仅保留该组的Success行
  • 若同一Id组内同时存在Pending和Failed状态,仅保留该组的Pending行
  • 若同一Id组内只有Failed状态,仅返回该组的第一行

示例表

IdStatus
1Success
1Pending
2Pending
2Failed
3Failed
3Failed

SQL解决方案

利用窗口函数给状态设置优先级,筛选出符合要求的行:

WITH ranked_data AS (
    SELECT 
        Id,
        Status,
        ROW_NUMBER() OVER (
            PARTITION BY Id 
            ORDER BY 
                CASE Status 
                    WHEN 'Success' THEN 1 
                    WHEN 'Pending' THEN 2 
                    WHEN 'Failed' THEN 3 
                END,
                Id -- 若需按原表顺序取Failed组首行,可替换为表的自增主键或其他排序字段
        ) AS rn
    FROM your_table_name -- 替换为你的表名
)
SELECT Id, Status
FROM ranked_data
WHERE rn = 1;

代码说明

  • 通过PARTITION BY Id将数据按Id分组
  • 用CASE语句定义状态优先级:Success(最高)> Pending > Failed(最低),排序后优先级最高的行排名为1
  • 对于仅含Failed的组,按指定规则(如Id升序)取第一行
  • 最后筛选出排名为1的行,即可满足所有筛选规则

伪代码参考

// 按Id分组处理每组数据
for each group in grouped_table by Id:
    status_list = [row.Status for row in group]
    if 'Success' in status_list and 'Pending' in status_list:
        output rows where Status == 'Success'
    elif 'Pending' in status_list and 'Failed' in status_list:
        output rows where Status == 'Pending'
    elif all(s == 'Failed' for s in status_list):
        output group[0] // 返回组内第一行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 02:03:12