[英]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.我正在开发一个 Android 应用程序,我在其中使用 Room 持久性库。 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.
在其中一个表(房间实体)中,我有一种情况,我想通过有条件地删除基于其他列的具有相同列值的其他记录来基于列 select 唯一记录。
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 SQL 查询的预期结果,如果其 S_ID 与另一个“待定”状态记录冲突,我希望从结果中删除具有“
Rejected'
状态的记录
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'
.这使用了字母顺序用于
max()
和'Pending' < 'Rejecdted'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.