获取仅与给定值列表关联的ID

时间:2019-05-13 13:11:44

标签: sql database db2

我有一张简单的桌子

customerid    clientid
----------------------
4567          1
5678          1
1298          2
4567          2
5678          2
4567          3 

我想只获取带有客户ID列表的clientid,所以说
(4567,5678)中的customerid应该为1,
(4567)clientid中的cutomerid应该为3

SELECT clientid 
FROM customer_client 
WHERE customerid IN (4567,5678) 
GROUP BY clientid 
HAVING COUNT(customerid) = 2

这将返回

clientid
---------
1
2

我想要的只是

clientid
---------
1

3 个答案:

答案 0 :(得分:1)

将条件移至having子句。如果没有重复,可以执行以下操作:

SELECT cc.clientid
FROM customer_client cc
GROUP BY cc.clientid
HAVING SUM(CASE WHEN cc.customerid IN (4567, 5678) THEN 1 ELSE 0 END) = COUNT(*) AND
       COUNT(*) = 2;

答案 1 :(得分:1)

试试这个-

SELECT DISTINCT clientid
FROM customer_client
WHERE customerid IN (4567,5678) 

EXCEPT 

SELECT DISTINCT clientid
FROM customer_client
WHERE  customerid NOT IN (4567,5678)

答案 2 :(得分:1)

with t (customerid, clientid) as (values
  (4567, 1)
, (5678, 1)
, (1298, 2)
, (4567, 2)
, (5678, 2)
, (4567, 3)
)
, l (customerid) as (values
--4567, 5678
--4567
4567, 5678, 1298
)
select g1.clientid
from (
  select t.clientid, count(1) cnt
  from t
  join l on l.customerid=t.customerid
  group by t.clientid
) g1
join (
  select clientid, count(1) cnt
  from t 
  group by clientid
) g2 on g1.clientid=g2.clientid and g1.cnt=g2.cnt and g1.cnt=(select count(1) from l);

您无需在相应ID列表中的select语句中的任何位置指定客户ID的数量(可能与示例中的不同)。
只是这些ID本身的列表。