Select 具有 NBR 1 和 2 的行在不同的行上的 ID

Select ID's that have rows with NBR 1 and 2 on separate rows

我想写 SQL 将 return 行,其中 VENDOR_ID 有一行 NBR_ID = 1 和另一行 NBR_ID = 2。在下面的示例中,SQL 将为 VENDOR_ID 93309A 提供 return 数据,其中一行为 NBR_ID 1 ,另一行为 NBR_ID 2.

GROUP_ID     VENDOR_ID    NBR_ID
AUX          27           1
AUX          87188A       1
AUX          92481A       1
AUX          92482A       1
AUX          92527A       1
AUX          93309A       1
AUX          93309A       2
AUX          93328A       1

我写了下面的 SQL,但这并不是特别 return VENDOR_ID 有一行 NBR_ID 为 1,另一行有 NBR_ID 共 2 个。

SELECT GROUP_ID, VENDOR_ID, NBR_ID
FROM TEST_TABLE
WHERE NBR_ID IN (1,2)

我如何才能更新到只有 return VENDOR_IDNBR_ID 在不同的行上?

您可以使用聚合:

SELECT GROUP_ID, VENDOR_ID
FROM TEST_TABLE
WHERE NBR_ID IN (1, 2)
GROUP BY GROUP_ID, VENDOR_ID
HAVING COUNT(DISTINCT NBR_ID) = 2;

这不 return NBR_ID 有两个原因。首先,你的问题没有说明你想要它。其次,它相当多余,因为你知道列表由 1 和 2 组成。

使用相关子查询

SELECT GROUP_ID,VENDOR_ID,NBR_ID
FROM TEST_TABLE a
WHERE exists(select 1 from TEST_TABLE b where a.GROUP_ID=b.group_id and 
a.VENDOR_ID=b.vendor_id and NBR_ID IN (1,2) 
having count(distinct nbr_id)=2) and NBR_ID IN (1,2) 

存在使用

select t1.* from TEST_TABLE t1
where exists ( select 1 from TEST_TABLE t2 where t1.VENDOR_ID=t2.VENDOR_ID
                                         and t1.GROUP_ID=t2.GROUP_ID
                                      and NBR_ID in (1,2)
                                      having count(distinct NBR_ID)=2)
and NBR_ID in (1,2)