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

按contractnumber筛选数据:优先取deviceid='all'行,无则取全部

需求说明

对于每个contractnumber,若存在deviceid='all'的行,则仅保留这些行;若不存在deviceid='all'的行,则保留该contractnumber对应的所有行。

原始表结构及数据
tenantcontractnumberdeviceidPricetype
120all0.051
120all0.022
120all0.073
120xy70.031
120xy70.0052
120xy70.043
120rq90.051
120rq90.022
125am60.041
125am60.032
125am60.063
期望结果
tenantcontractnumberdeviceidPricetype
120all0.051
120all0.022
120all0.073
125am60.041
125am60.032
125am60.063
解决方案

以下提供两种可行的SQL实现方式:

方式一:使用EXISTS子查询

SELECT t.*
FROM your_table t
WHERE 
    t.deviceid = 'all'
    OR NOT EXISTS (
        SELECT 1
        FROM your_table t2
        WHERE t2.contractnumber = t.contractnumber
          AND t2.deviceid = 'all'
    );

逻辑:直接筛选出deviceid='all'的行,或者当前contractnumber下没有deviceid='all'记录的所有行。

方式二:使用窗口函数标记

WITH contract_flags AS (
    SELECT 
        *,
        COUNT(CASE WHEN deviceid = 'all' THEN 1 END) OVER (PARTITION BY contractnumber) AS has_all
    FROM your_table
)
SELECT tenant, contractnumber, deviceid, Price, type
FROM contract_flags
WHERE has_all = 0 OR deviceid = 'all';

逻辑:先通过窗口函数统计每个contractnumber下是否存在deviceid='all'的行(has_all>0表示存在),再筛选出无all记录的所有行,或本身就是deviceid='all'的行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:30:57