查询按一列中的值进行分组,并确定第二列中的特定值是否在每个组中至少出现一次

时间:2018-04-05 17:50:02

标签: sql sql-server sql-server-2008

这与我在此问题中收到的结果有关: 查询显示一个表以及哪些行与另一个表匹配的指示 对于一些查询结果或我试图识别的表,对于每个Box id,如果该Box ID的所有实例在另一列中都有“是”,或者至少有一个“否”。所有的肯定会导致肯定,任何不会导致否。 例如 如果这是一张桌子: ID,Box,Match 1,Box100,是的 2,Box100,是的 3,Box100,是的 4,Box200,是的 5,Box200,没有 6,Box200,是的 7,Box300,是的 8,Box300,是的 9,Box300,是的 10,Box400,没有 11,Box400,没有 12,Box400,是的 提供这些结果的查询是什么 Box100,是的 Box200,没有 Box300,是的 Box400,没有 我尝试将两个查询联合起来,一个用于no的yes,使用UNIQUE语句只返回一个,但当然返回: Box100,是的 Box200,是的 Box200,没有 Box300,是的 Box400,是的 Box400,没有 这不是我要找的。 我还发现这很难确定要称之为什么,因此寻找解决方案,因此我可能是令人费解的标题。所以请提前道歉。 我觉得这个解决方案可能很简单,但我无法完全理解它。 谢谢

2 个答案:

答案 0 :(得分:3)

假设noyes是字符串,您只需使用聚合:

select box, min(match) as match
from t
group by box;

这是因为值的字母顺序。更通用的解决方案是:

select box,
       (case when sum(case when match = 'no' then 1 else 0 end) > 0
             then 'no' else 'yes'
        end) as match
from t
group by box;

答案 1 :(得分:0)

戈登的回答是我最有可能使用的,但你可以这样做....

spark.submit.deployMode=cluster
  

结果集:

declare @example as table (
    exampleID int identity(1,1) not null primary key clustered
,   box       varchar(255) not null
,   match     varchar(25) not null
);

insert into @example (box, match) 

select 'Box100', 'yes' union all
select 'Box100', 'yes' union all
select 'Box100', 'yes' union all
select 'Box200', 'yes' union all
select 'Box200', 'no' union all
select 'Box200', 'yes' union all
select 'Box300', 'yes' union all
select 'Box300', 'yes' union all
select 'Box300', 'yes' union all
select 'Box400', 'no' union all
select 'Box400', 'no' union all
select 'Box400', 'yes';

    select distinct a.box
         , isnull(b.match, c.match) match
      from @example a
 left join @example b
        on a.box = b.box
       and b.match = 'no'
 left join @example c
        on a.box = c.box
       and c.match = 'yes'