简体   繁体   中英

Select unique Records based on a column by conditionally removing the other record having same column value based on some other coumn in sql

I am developing an Android app in which I am using the Room persistence library. In one of the Tables (Room Entity), I have a case where I want to select unique Records based on a column by conditionally removing the other record having the same column value based on some other column.

Consider the following table as a base.

S_ID STATUS
1 Pending
1 Rejected
3 Approved
4 Approved
5 Pending
6 Rejected
7 Rejected

the expected result of the SQL query where I want a record with ' Rejected' status to be removed from results if its S_ID collides with another 'Pending' status record

S_ID STATUS
1 Pending
3 Approved
4 Approved
5 Pending
6 Rejected
7 Rejected

what I have tried so far:

select DISTINCT s_id OR s_id = 0, * from TABLE1

I think You can try below query:

SELECT * FROM table1 WHERE table1.S_ID in (SELECT S_ID FROM table1 GROUP BY S_ID HAVING COUNT(S_ID)>0) and table1.[status]<>'Rejected'

Edited:

SELECT table1.S_ID, 
(select Alias.[Status] from Table1 Alias where Alias.S_ID=table1.S_ID  
and ((COUNT(table1.S_ID)>1 and Alias.[Status]<>'Rejected') or COUNT(table1.S_ID)=1) 
) as [Status]
FROM table1 GROUP BY S_ID HAVING COUNT(S_ID)>0

You can use aggregation for this:

select s_id, min(status) as status
from table_id
group by s_id;

This uses the fact that alphabetical ordering is used for max() and 'Pending' < 'Rejecdted' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM