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

SQL中如何为COALESCE生成的the_id添加条件前缀以区分值来源

SQL修改实现方案

直接用CASE条件判断替换原有COALESCE逻辑即可,通过判断grouped_wells.groupforecasting_id是否非空,拼接对应前缀,就能避免数值相同的不同来源ID被分到同一组。

核心修改逻辑

the_id字段的生成逻辑替换为:

CASE
    WHEN grouped_wells.groupforecasting_id IS NOT NULL THEN CONCAT('group_', grouped_wells.groupforecasting_id)
    ELSE CONCAT('well_', wells.id)
END AS the_id

修改后完整SQL

SELECT 
    CASE
        WHEN grouped_wells.groupforecasting_id IS NOT NULL THEN CONCAT('group_', grouped_wells.groupforecasting_id)
        ELSE CONCAT('well_', wells.id)
    END AS the_id,
    string_agg(wells.name,', ') as well_name,
    sum(gas_cd) as gas_cd,
    date 
FROM productions
INNER JOIN completions on completions.id = productions.completion_id 
INNER JOIN wellbores on wellbores.id = completions.wellbore_id 
INNER JOIN wells on wells.id = wellbores.well_id 
INNER JOIN fields on fields.id = wells.field_id 
INNER JOIN clusters on clusters.id = fields.cluster_id
LEFT JOIN grouped_wells on grouped_wells.wells_id = wells.id
LEFT JOIN groupforecasting on groupforecasting.id = grouped_wells.groupforecasting_id and groupforecasting.workspace_id = 3
GROUP BY the_id, productions.date
ORDER BY the_id, productions.date

兼容说明

如果你使用Oracle数据库,拼接语法需要调整为双竖线写法:

CASE
    WHEN grouped_wells.groupforecasting_id IS NOT NULL THEN 'group_' || grouped_wells.groupforecasting_id
    ELSE 'well_' || wells.id
END AS the_id

内容的提问来源于stack exchange,提问作者Sami Al-Subhi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:54:05