postgres SQL中有一个命令,就像“NOT”命令一样吗?

时间:2011-02-04 07:51:26

标签: sql command

例如:

Apple is a and b
Banana is a and b
Orange is a

我正在尝试编写一个命令,它只会显示只有b而不是b的内容。

2 个答案:

答案 0 :(得分:1)

表格结构

Fruit | Attribute
Apple   A
Apple   B
Banana  A
Banana  B
Orange  A

查询

select t1.* from tbl t1
where t1.attribute = 'A'
and not exists (select * from tbl t2
                where t2.fruit=t1.fruit and t2.attribute <> 'A')

答案 1 :(得分:0)

现在只是'sql'标签,所以这是标准SQL-2003:

WITH tbl (Fruit, Attribute)
     AS
     (
      SELECT Fruit, Attribute
        FROM (
              VALUES ('Apple', 'A'), 
                     ('Apple', 'B'), 
                     ('Banana', 'A'), 
                     ('Banana', 'B'), 
                     ('Orange', 'A')
             ) AS tbl (Fruit, Attribute)
     )
SELECT T1.Fruit, T1.Attribute
  FROM tbl AS T1
 WHERE T1.Attribute = 'A'
       AND 1 = (
                SELECT COUNT(*)
                  FROM tbl AS T2
                 WHERE T2.Fruit = T1.Fruit
               );