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

筛选匹配指定TemplateId全部条件的StoreNbr的SQL查询问题

筛选匹配模板全部条件的门店编号

表结构

表名字段信息关联说明
ConditionAttributesConditionAttributeId (PK, int)
Name (varchar(100))
基础条件属性表
StoreAttributesId (PK, uniqueidentifier)
StoreNbr (string)
ConditionAttributeId (FK)
门店关联条件属性,一对多关联ConditionAttributes
TemplateConditionsId (PK, uniqueidentifier)
TemplateId (uniqueidentifier)
ConditionAttributeId (FK)
模板关联条件属性,一对多关联ConditionAttributes

示例数据集

StoreAttributes 数据

StoreNbrConditionAttributeId
57051
57052
57072
57053
57063

TemplateConditions 数据

IdTemplateIdConditionAttributeId
105781
109782
500783

需求

仅筛选出**完全匹配TemplateId=78对应所有ConditionAttributeId**的门店编号,即仅返回5705。

原语句问题

原SQL使用IN子查询,仅能返回至少匹配一个模板条件的门店,无法满足“全部匹配”的要求:

Select Distinct StoreNbr 
From StoreAttributes st
Where ConditionAttributeId in (Select ConditionAttributeId 
                               From TemplateConditions 
                               Where TemplateId = 78); 

解决方案

方法1:分组统计匹配数对比

通过关联门店与模板条件,分组后统计每个门店匹配的条件数量,与模板总条件数相等则判定为完全匹配:

SELECT st.StoreNbr
FROM StoreAttributes st
JOIN TemplateConditions tc 
  ON st.ConditionAttributeId = tc.ConditionAttributeId
WHERE tc.TemplateId = 78
GROUP BY st.StoreNbr
HAVING COUNT(DISTINCT st.ConditionAttributeId) = (
    SELECT COUNT(DISTINCT ConditionAttributeId)
    FROM TemplateConditions
    WHERE TemplateId = 78
);

方法2:双重NOT EXISTS排除法

排除存在模板条件但门店未匹配的情况,剩余即为完全匹配的门店:

SELECT DISTINCT st.StoreNbr
FROM StoreAttributes st
WHERE NOT EXISTS (
    SELECT 1
    FROM TemplateConditions tc
    WHERE tc.TemplateId = 78
    AND NOT EXISTS (
        SELECT 1
        FROM StoreAttributes st2
        WHERE st2.StoreNbr = st.StoreNbr
        AND st2.ConditionAttributeId = tc.ConditionAttributeId
    )
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:18:10