如何找到具有不同 id 的两个查询的并集
How to find union of two query with distinct id
我有 table 配置文件包含该配置文件的状态,即活动和非活动
请注意,一个 csr_id 有多个非活动状态记录,但肯定只有一个或 none 状态为活动
的记录
table供您参考:-
id | status | csr_id |
---+-----------+---------
1 | inactive | 1
2 | inactive | 1
3 | inactive | 1
4 | inactive | 1
5 | inactive | 2
6 | inactive | 2
7 | inactive | 2
8 | inactive | 2
9 | active | 2
查询参考:-
(select * from profile where csr_id IN (2,1) AND status = 'active')
UNION
(select DISTINCT ON (csr_id) *from profile where csr_id IN (2,1) AND status = 'inactive') order by status
结果:-
id | status | csr_id |
-----+----------+---------------+--------
9 | active | 2
4 | inactive | 1
8 | inactive | 2
预期结果:-
id | status | csr_id |
-----+----------+---------
9 | active | 2
4 | inactive | 1
因为 csr_id 2 处于活动状态,因此忽略 csr_id 2
的非活动条目
有什么解决办法吗?
您只能使用 distinct on
执行此操作:
select distinct on (csr_id) p.*
from profile p
order by csr_id, status, id desc
升序active
上的order by
子句将活动记录放在第一位,然后优先考虑最大id
的记录。
id | status | csr_id
-: | :------- | -----:
4 | inactive | 1
9 | active | 2
我有 table 配置文件包含该配置文件的状态,即活动和非活动 请注意,一个 csr_id 有多个非活动状态记录,但肯定只有一个或 none 状态为活动
的记录table供您参考:-
id | status | csr_id |
---+-----------+---------
1 | inactive | 1
2 | inactive | 1
3 | inactive | 1
4 | inactive | 1
5 | inactive | 2
6 | inactive | 2
7 | inactive | 2
8 | inactive | 2
9 | active | 2
查询参考:-
(select * from profile where csr_id IN (2,1) AND status = 'active')
UNION
(select DISTINCT ON (csr_id) *from profile where csr_id IN (2,1) AND status = 'inactive') order by status
结果:-
id | status | csr_id |
-----+----------+---------------+--------
9 | active | 2
4 | inactive | 1
8 | inactive | 2
预期结果:-
id | status | csr_id |
-----+----------+---------
9 | active | 2
4 | inactive | 1
因为 csr_id 2 处于活动状态,因此忽略 csr_id 2
的非活动条目有什么解决办法吗?
您只能使用 distinct on
执行此操作:
select distinct on (csr_id) p.*
from profile p
order by csr_id, status, id desc
升序active
上的order by
子句将活动记录放在第一位,然后优先考虑最大id
的记录。
id | status | csr_id -: | :------- | -----: 4 | inactive | 1 9 | active | 2