SQL 查询以在某些 ID 设置为特定状态时选择与另一个组 ID 相关的 ID

SQL Query to pick up IDs that are related to another Group ID when some are set to a certain status

这个标题的描述有点复杂,但我会尽力在这里更好地解释它。我有以下数据。

+---------+----------+--------+
| GroupID | UniqueID | Status |
+---------+----------+--------+
|       1 |        1 |      3 |
|       1 |        2 |      3 |
|       1 |        3 |      2 |
|       2 |        4 |      3 |
|       2 |        5 |      3 |
|       3 |        6 |      1 |
|       3 |        7 |      1 |
+---------+----------+--------+

组 ID 是 link 行的共享键。 唯一 ID 是一个完全唯一的密钥。 状态是一个值字段。

我已经考虑这个查询一段时间了,但我就是想不通我可以做些什么来获得我想要的结果。

我想 return 状态为 3 的订单的所有唯一 ID。除此之外,这些订单必须至少有一个订单 link通过 GroupID 设置为 1 或 2。

所以对于 GroupID“1”,我们有 3 条记录: 第一行的状态为 3,同一组中的另一个订单设置为 1 或 2。(包括在结果中)。 第二行的状态和同一组中的另一个订单设置为 1 或 2。(包括在结果中)。 第三行的状态为 2,因此未包含在结果中。

所以对于 GroupID“2”,我们有 2 条记录: 两条记录的状态均为“3”,但没有状态为“1”或“2”的记录,因此它们未显示在结果中。

所以继续这个逻辑,对于示例数据,输出应该是:

+---------+----------+--------+
| GroupID | UniqueID | Status |
+---------+----------+--------+
|       1 |        1 |      3 |
|       1 |        2 |      3 |
+---------+----------+--------+

如果我需要进一步澄清,请告诉我。

试试这个:

select
    *
from
    yourtable
where
    Status = 3
    and GroupId in
    (
        select distinct
            GroupID
        from
            yourtable
        where
            Status <> 3
    )

你的样本数据和解释不一致。

如果您想要只有“3”的行,则:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.groupid = t.groupid and t2.status <> 3
                 );

我知道您想要处于状态 3 的行,其中另一行具有相同的组和另一个状态。一种选择使用 exists:

select t.*
from mytable t
where status = 3 and exists (
    select 1
    from mytable t1
    where t1.groupid = t.groupid and t1.status <> t.status
)

您还可以使用 window 函数:

select groupid, uniqueid, status
from (
    select t.*,
        min(status) over(partition by groupid) min_status,
        max(status) over(partition by groupid) max_status
    from mytable t
) t
where status = 3 and min_status <> max_status