查询使用值x的其他对应元素查找元组

时间:2011-03-13 14:39:45

标签: sql postgresql

如果我们有下表称为数据:
(id, n1, n2, n3, n4)
111, 2, 4, 7, 0
444, 1, 1, 2, 1
555, 1, 1, 2, 0
777, 5, 3, 8, 0

我们如何只获得(2,4,7)和(5,3,8)?

SELECT DISTINCT n1,n2,n3  
FROM data  
WHERE n4 = 0;  

不起作用,因为它也返回(1,1,2)元组。我只需要一直有n4 = 0的元组。

5 个答案:

答案 0 :(得分:2)

其中一个选项是使用EXCEPT

SELECT n1, n2, n3
FROM data
WHERE n4 = 0

EXCEPT

SELECT n1, n2, n3
FROM data
WHERE n4 <> 0

答案 1 :(得分:1)

SELECT
    d.n1, d.n2, d.n3
FROM
    data d
WHERE
    d.n4 = 0
    AND
    NOT EXISTS (SELECT *
      FROM
          data d2
      WHERE
          d.id = d2.id
          AND
          --3 columns = 3 pairs. n1-n2, n1-n3, n2-n3
          (d.n1 = d2.n2 OR d.n1 = d2.n3 OR d.n1 = d2.n3))

编辑:

如果1,1,2与1,2,1不同,那么

SELECT
    MIN(id), n1, n2, n3
FROM
    data
WHERE
    n4 = 0
GROUP BY
    n1, n2, n3
HAVING
    COUNT(*) = 1

答案 2 :(得分:0)

你可以使用JOIN来实现自我:

SELECT d.n1, d.n2, d.n3
FROM data d
LEFT JOIN data d2 ON (d.n1 = d2.n1 AND d.n2 = d2.n2 AND d.n3 = d3.n3 AND d.n4 != d2.n4)
WHERE n4 = 0 AND d2.id IS NULL

答案 3 :(得分:0)

测试平台:

create table data(id integer, n1 integer, n2 integer, n3 integer, n4 integer);

insert into data(id, n1, n2, n3, n4)
values (111, 2, 4, 7, 0), (444, 1, 1, 2, 1), 
       (555, 1, 1, 2, 0), (777, 5, 3, 8, 0);

假设n4不能为空或否定:

select n1, n2, n3 from data group by n1, n2, n3 having max(n4)=0;

 n1 | n2 | n3
----+----+----
  2 |  4 |  7
  5 |  3 |  8
(2 rows)

如果您不能认为:

insert into data(id, n1, n2, n3, n4)
values (881, 1, 1, 1, -1), (882, 1, 1, 1, null), (883, 1, 1, 1, 0);

select n1, n2, n3
from data
group by n1, n2, n3
having sum(case when n4=0 then 0 else 1 end)=0;

 n1 | n2 | n3
----+----+----
  2 |  4 |  7
  5 |  3 |  8
(2 rows)

答案 4 :(得分:0)

似乎相当简单:

SELECT n1,
       n2,
       n3
FROM   data
GROUP  BY n1,
          n2,
          n3
HAVING Max(n4)=0 AND MIN(n4)=0;

这将仅基于n1,n2,n3元组进行选择,并且元组的所有n4值均为0