【问题标题】:How to write a filter to check for distinct values如何编写过滤器来检查不同的值
【发布时间】:2026-02-11 19:30:01
【问题描述】:

我有一张很大的桌子,其中一部分看起来像这样。在“配方”列中是在“站点”列中列出的两个工厂使用的配方。我想检查一下站点 B 生产的所有食谱是否也在站点 A 生产,或者站点 B 是否有一些只有它使用的“不同”食谱。

Recipe Site
X001 A
X001 A
X002 A
X002 B
X002 B
X003 A

【问题讨论】:

  • 根据问题指南,请展示您的尝试并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。
  • 您对给定样本的预期结果是什么?
  • 这里的“非常大”有多大?行数是多少
  • 使用 EXCEPT 运算符。在伪代码中:为站点 B 选择行 为站点 A(或所有其他站点 - 选择您的逻辑应该有多灵活)选择行。

标签: sql sql-server filter


【解决方案1】:

虽然不一定直观,但 GROUP BY 在这样的场景中会发挥作用。

这是对问题的简单直接回答

select     Recipe
        
from       t

group by   Recipe

having     count(case Site when 'B' then 1 end) > 0
       and count(case Site when 'A' then 1 end) = 0

以下查询将为您提供详细视图

select   Recipe
        ,max(case Site when 'A' then 'V' end) as A_exists
        ,max(case Site when 'B' then 'V' end) as B_exists
        ,count(*)                             as total_count
        ,count(case Site when 'A' then 1 end) as A_count
        ,count(case Site when 'B' then 1 end) as B_count
        
from     t

group by Recipe

以下查询将为您提供摘要视图

with t2 as
(
    select   max(case Site when 'A' then 'V' end) as A_exists
            ,max(case Site when 'B' then 'V' end) as B_exists
        
    from     t

    group by Recipe
)
select      A_exists
           ,B_exists
           ,count(*) as total_Recipes

from        t2

group by    A_exists
           ,B_exists

fiddle
请注意,我在示例中添加了一些行以使其更有趣

【讨论】: