SQL查询检索组记录

时间:2015-02-13 00:59:48

标签: sql

我不确定如何描述这个,但我正在尝试检索所有具有公共索引并在单独字段中具有特定值的记录...

表:回应

responseID     objective   
===============================
AAA            Posted          
AAA            Aligned      
AAB            Aligned
AAB            Null
AAC            Posted
AAC            Null

根据目标字段中的“已发布”值,查询将从表格响应中返回以下内容:

responseID     objective   
===============================
AAA            Posted          
AAA            Aligned      
AAC            Posted
AAC            Null

非常感谢任何帮助。特别是对词汇术语的帮助,因为我只是从查询开始。

4 个答案:

答案 0 :(得分:2)

您正在寻找responseId中有值的任何键的行,并且已发布'在objective列中。 SQL术语是"存在" - 此查询中是否存在任何行?

这应该可以正常工作:

DECLARE VARCHAR(50) @objective = 'Posted';

select data1.*
from data data1
where exists 
(
  select 1
  from data data2
  where data2.responseid = data1.responseid 
    and data2.objective = @objective
);

这里是SQLFiddle showing that it works in MS SQL Server 2012

答案 1 :(得分:1)

select r.responseid, r.objective
  from response r
  join (select responseid from response where objective = 'Posted') v
    on r.responseid = v.responseid

答案 2 :(得分:0)

使用exists运算符获取具有目标Response的{​​{1}}。

'Posted'

答案 3 :(得分:0)

我认为您可以使用exists做您想做的事情 - 也就是说,获取其中一个目标为Posted的所有回复:

select r.*
from response r
where exists (select 1
              from response r2
              where r2.responseid = r.responseid and r2.objective = 'Posted'
             );
相关问题