我想选择包含值且不包含值的UserId

时间:2018-04-28 02:29:53

标签: sql-server

我有一张桌子M_In 它有两列UserId,MeFr 我想选择包含值( 123 )且不包含值( 456 )或其他值的UserId

示例表M_In

UserId  MeFr
------------
100     *123*
100     *456*
100     *123*
200     *123*
200     *456*
300     *123*

预期输出

UserId  MeFr
------------
300     *123*

我想使用此方法示例

实施例

Select * from     
  (select i.*,                                   
         row_number() over (partition by UserId order by UserId ) as rn
  from M_In i 
   ) i 
   left join  
   (select o.*,                                   
         row_number() over (partition by UserId order by UserId ) as rn
  from M_In o
  ) o  on o.UserId = i.UserId
 where not EXISTS 

2 个答案:

答案 0 :(得分:2)

使用NOT EXISTS()

SELECT *
FROM   M_In m
WHERE  m.MeFr = 123
AND    NOT EXISTS
       (
           SELECT *
           FROM   M_In x
           WHERE  x.UserId = m.UserId
           AND    x.MeFr   <> 123
       )

答案 1 :(得分:1)

简单的联接应该在这里完成工作:

SELECT m.*
FROM   M_In m
join M_In m1 on m.UserId = m1.UserId
WHERE  m.MeFr = 123 and m1.MeFr <> 123