1

I need help to write this in SQL:

I have one table and I would like to select No with Chars A, B or C, but if I have A and B for same No I want to show only B, else I need to show all.

Pseudo code:

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

Example:

Table1

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

I want result:

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

Is it clear enough what I need?

1 Answer 1

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')

I changed Char in Ch as Char might be a reserved KeyWord...

Tested with Sql Server, but the query is, I think, ANSI SQL

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

or

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'))
Sign up to request clarification or add additional context in comments.

2 Comments

Both work work PostgreSQL, second is the better one. (Why not test with PostgreSQL on sqlfiddle?)
Because I'm quite sure about ANSI SQL, but not so sure about PostgreSQL types (bad argument... I know, I know) ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.