根据多个值SQL选择行

时间:2012-05-31 15:28:31

标签: select where postgresql-9.1

我需要帮助才能在SQL中写这个:

我有一张桌子,我想选择不带字母A,B或C,但是如果我有A和B同样不,我想只显示B,否则我需要显示所有。

伪代码:

SELECT *
  FROM Table1
  WHERE IF EXISTS (Char = A and Char = B)
    THEN Char IN (B, C)
    ELSE Char IN (A, B, C)

示例:

表1

ID  No     Char
1   10     A
2   10     B
4   10     C
5   11     A
6   11     D
7   12     C

我想要结果:

ID  No     Char
2   10     B
4   10     C
5   11     A
7   12     C

我需要的是否足够明确?

1 个答案:

答案 0 :(得分:3)

select t1.Id, t1.No, t1.Ch from Table1 t1
where t1.Ch IN ( 'B', 'C')
UNION
select t1.Id, t1.No, t1.Ch from Table1 t1
where t1.Ch ='A' 
and not exists (select null from Table1 t2 where t2.No = t1.No  and t2.Ch='B')

我改变了Char in Ch,因为Char可能是一个保留的KeyWord ......

使用Sql Server进行测试,但我认为查询是ANSI SQL

http://sqlfiddle.com/#!3/f2145/12

select t1.Id, t1.No, t1.Ch from Table1 t1
where t1.Ch IN ( 'B', 'C')
OR (t1.Ch ='A'
and not exists (select null from Table1 t2 where t2.No = t1.No  and t2.Ch='B'))