Pez Cuckow
Pez Cuckow

Reputation: 14422

SQL Ignore null value if a row with the same ID exists

I have a Sybase table with the following data (example):

Users:

 ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     1            (null)              
 65823     2            187                 
 91817     1            (null)                         
 37950     1            773                 
 37950     1            (null)              
 37968     1            (null)              
 37968     1            773                                
 72576     1            (null)              
 72576     1            (null)                

I want to return all combination of the users and type's but if there is more than one example of a particular user/type combination only show the record that isn't null.

E.g. the above table should return the following

 ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     1            (null)           - although this is null the type/id is unique   
 65823     2            187              
 91817     1            (null)           - this is null but is a unique type/id              
 37950     1            773                                         
 37968     1            773              - this is included and the id/type that has a null player id isn't                              
 72576     1            (null)           - this is a unique type/id

So far I've looked into queries using group by, having and inner joins but have been unable to find a way to match the results I'm looking for.

I've also looked at things like group by, and then using max on the PlayerID, but aggregate functions ignore null values.

How can I return the unique id/type pairs with their player id?

--

Question from Paul:

ID        Type         PlayerID
 --------  -----------  ------------------- 
 65823     2            187                        
 37950     1            773                                         
 37968     1            773    

Upvotes: 0

Views: 3477

Answers (2)

gaborsch
gaborsch

Reputation: 15758

From SQL side you can do like:

select * from mytable t1 where playerId is not null
union
select * from mytable t2 where playerid is null 
   and not exists (
          select * from mytable t3 where t2.id=t2.id and t2.type=t3.type
       )

I don't know how effective it will be, but it will give you the result you want.

Upvotes: 1

paul
paul

Reputation: 22001

What does

select  ID, type, max(PlayerID)
from    Users
group by ID, type

return? (I have never used sybase)

Upvotes: 0

Related Questions