SQL 以筛选器识别某些列不同的 ID

SQL to identify the IDs for which some columns are different with a filter

假设我有以下 table:

   id | temp_id | status     | date
------+---------+------------+-----------
0  10 | 123-abc |   closed   | 2021-11-01
1  12 | 123-abc |   open     | 2021-10-26
2  14 | 123-abc |   null     |    null
3  15 | 123-abc |   open     | 2021-10-26
4  17 | 123-abc |   open     | 2021-10-26
5  20 | 456-xyz |   open     | 2021-10-29
6  22 | 456-xyz |   null     |    null
7  20 | 789-uvw |   closed   | 2021-10-06
8  22 | 789-uvw |   closed   | 2021-10-06

我想编写一个查询来从 table 中查找所有 temp_ids,其中某些列(状态、日期)的值与相同的 temp_id 不匹配,如果其中至少有一个状态 = 'closed'

对于此 table,它应该 return 在临时 ID 列中只有 123-abc,例如:

   | temp_id | 
---+---------+
0  | 123-abc | 

在这里,我不希望结果是 456-xyz,因为即使 id 20 和 22 具有相同的 temp_id 和不同的状态、日期值 - 但两者都没有状态 'closed' 所以这不是最终结果所必需的。而对于 789-uvw,两条记录(7 和 8)的状态都是已关闭且日期相同,因此也不需要。

到目前为止我的想法是: 我正在使用由 temp_id 分区的 row_number 但在上面的示例中,我如何比较 row_number 1 和 5 的 temp_id = '123-abc' 并查看它们中的任何一个状态 = 'closed'。我试过 any() 但它抛出错误,我想我没有正确使用它。任何帮助将不胜感激。谢谢

使用 HAVING 非常简单:

select
temp_id
from
<your table>
where temp_id in (select temp_id from <your table> where status = 'closed')
group by temp_id
having count (distinct status) > 1
or count (distinct date) > 1

DBFiddle