2

How to retrieve all rows having value in a status column (not null) group by ID column.

Id      Name    Status
1394    Test 1  Y
1394    Test 2  null    
1394    Test 3  null    
1395    Test 4  Y
1395    Test 5  Y

I wrote like select * from table where status = 'Y'. It brings me 3 records, how to add condition to bring in only last 2? the 1394 ID have other 2 records, which status is null.

0

5 Answers 5

3

If you want to select groups where the status is only y, you can do:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and
                        (t2.Status <> 'Y' or t2.status is null)
                 );

If you only want the ids, I would use group by and having:

select id
from t
group by id
having min(status) = 'Y' and max(status) = 'Y' and count(*) = count(status);

The last condition checks for no NULL values.

You could also write:

having min(status = 'Y' then 1 else 0 end) = 1
Sign up to request clarification or add additional context in comments.

Comments

2

A simple way is:

select * from mytable
where status = 'Y'
and id not in (select id from mytable where status is null)

2 Comments

Using 'not in' clauses while a 'simple way' is typically not well-performing....an outer-join to the collection of null-status Ids is preferred.
@jason this is easier to understand and unless the data volume is massive this will perform just fine. Often the optimiser will convert this to a join anyway, so performance can be the same as a coded join.
0

The existing query "where status = 'Y'" will bring you not null by definition.

If you are trying to get grouped results, a "GROUP BY id" clause will achieve this, which will also require putting id in the select explicitly instead of "*".

Example: SELECT id, COUNT(id) from table where status = 'Y'

Comments

0

If I am reading this correctly you want to bring in the ID for a grouping that never has a NULL status value:

I would use a subquery with a not-exist:

SELECT DISTINCT ID FROM mytable WHERE status IS NULL;

Then filter IDs that do not exist in that list:

SELECT * FROM mytable WHERE id NOT IN (SELECT DISTINCT ID FROM mytable WHERE status IS NULL);

Comments

0

Here are some possible solutions, because I am unclear on exactly what you want as output:

Select Id, Name, Status from table where status is not null;  

results in 3 rows:

 Id      Name    Status
1394    Test 1    Y 
1395    Test 4    Y
1395    Test 5    Y


Select Id, count(*) as anAmt from table where status is not null group by Id;  
    /* only retrieves counts per Id */

results in 1 row for each Id:

Id         anAmt
1394         1
1395         2

Comments

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.