如何使用\

时间:2017-08-14 16:13:32

标签: sql db2

cust_id | acc_type
--------------------
   1     |   L1
--------------------
   1     |   M1
--------------------
   1     |   O1
--------------------
   2     |   R1
--------------------
   3     |   S1
--------------------

需要的结果是

 cust_id | acc_type
--------------------
   1     |   L1
--------------------
   1     |   M1
--------------------

即使用单个cust_id我需要这两个值。当我使用group by i得到所有3个映射到1.请帮我解决这个问题在db2 \ sql

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM yourTable
WHERE cust_id IN (SELECT cust_id 
                  FROM yourTable 
                  WHERE acc_type in ('L1', 'M1')
                  GROUP BY cust_id 
                  HAVING COUNT(*) = 2 )

如果可以重复acc_type那么

                  HAVING COUNT(DISTINCT acc_type ) = 2

答案 1 :(得分:0)

根据您的评论,您似乎想要:

select t.*
from t
where (t.acc_type = 'L1' and
       exists (select 1 from t t2 where t2.cust_id = t.cust_id and t2.acc_type = 'M1')
      ) or
      (t.acc_type = 'M1' and
       exists (select 1 from t t2 where t2.cust_id = t.cust_id and t2.acc_type = 'L1')
      ) ;

对于此查询,您需要t(cust_id, acc_type)上的索引。