在一条记录中选择条件为真的记录

时间:2017-11-10 21:53:58

标签: sql sql-server

我需要从下表中的行中选择cid,project和owner,其中cid / project组合的一行或多行拥有1的所有者。

cid | project | phase | task | owner
-----------------------------------
1   | 1       | 1     | 1    | 1
1   | 1       | 1     | 2    | 2
1   | 1       | 1     | 3    | 2
2   | 1       | 1     | 1    | 1
2   | 1       | 1     | 2    | 1
3   | 1       | 1     | 3    | 2

我的输出表应如下所示:

cid | project | phase | task | owner
-----------------------------------
1   | 1       | 1     | 1    | 1
1   | 1       | 1     | 2    | 2
1   | 1       | 1     | 3    | 2
2   | 1       | 1     | 1    | 1
2   | 1       | 1     | 2    | 1

以下查询是我提出的。它似乎确实测试好了,但我的信心很低。查询是解决问题的有效方法吗?

select task1.cid, task1.project, task1.owner
from 
(select cid, project, owner from table) task1
right join 
(select distinct cid, project, owner from table where owner = 1) task2
on task1.cid = task2.cid and task1.project = task2.project

(我没有从示例输出中删除阶段和任务列,因此更容易比较。)

1 个答案:

答案 0 :(得分:2)

您只需使用IN子句

即可
  select cid, project, owner
  from table
  where cid in (select distinct id from table where owner = 1)

或带子查询的内部联接

  select a.cid, a.project, a.owner
  from table a 
  INNER JOIN ( select distinct cid , project
        from table where owner = 1
  ) t on t.cid = a.cid and t.project = a.project