问题描述
这是一个标题的复杂描述,但是我会在这里尝试更好地解释它。我有以下数据。
+---------+----------+--------+
| 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是将行链接在一起的共享密钥。 唯一ID是一个完全唯一的密钥。 状态是一个值字段。
我已经在考虑这个查询了一段时间了,但是我只是不知道该怎么做才能获得想要的结果。
我想返回状态为3的订单的所有唯一ID。此外,这些订单必须至少具有一个通过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 |
+---------+----------+--------+
让我知道是否需要进一步澄清。
解决方法
我了解您想要状态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
)
您还可以使用窗口功能:
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
,
尝试一下:
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
);