一张表如下姓名                 地区
---------------  ----------------
张三                 北京
张三                 上海
李四                 北京
王五                 北京我现在想实现,检索出地区同时为北京和上海的人员,也就是检索出“张三”
请问如何做到?谢谢~~

解决方案 »

  1.   

    select   *  from  t
    where 姓名='张三'
      

  2.   

    select 姓名
    from table
    where 地区 =  '北京' 
    and 姓名 in (select 姓名
                 from table
                 where 地区 =  '上海')
      

  3.   

    select distinct a.姓名 
    from 表名 a 
    where 
        exists(select 1 from 表名 where 姓名=a.姓名 and 地区='北京')
        and
        exists(select 1 from 表名 where 姓名=a.姓名 and 地区='上海')
      

  4.   

    declare @t table(姓名 varchar(10),地区 varchar(10))
    insert into @t select '张三','北京'
    union all select '张三','上海'
    union all select '李四','北京'
    union all select '王五','北京'select distinct 姓名 from @t a where exists(select * from @t where 姓名=a.姓名 and 地区<>a.地区)
      

  5.   

    declare @t table(a1 varchar(10),a2 varchar(10))
    insert into  @t
    select '张三','北京' union all
    select '张三','上海' union all
    select '李四','北京' union all
    select '王五','北京' select  a1  
    from  @t
    group by a1
    having count(distinct a2 )>1
      

  6.   

    select 姓名
    from (select 姓名
          from table
          where 地区 =  '北京') a
    join (select 姓名
          from table
          where 地区 =  '上海') b
    on a.姓名 = b.姓名
      

  7.   

    declare @t table(姓名 varchar(10),地区 varchar(10))
    insert into @t select '张三','北京'
    union all select '张三','上海'
    union all select '李四','北京'
    union all select '王五','北京'select * from @t a where exists(select * from @t where 姓名=a.姓名 and 地区='上海') and 地区='北京'
      

  8.   

    select distinct a.姓名 
    from 表名 a 
    where 
        exists(select 1 from 表名 where 姓名=a.姓名 and 地区='北京')
        and
        exists(select 1 from 表名 where 姓名=a.姓名 and 地区='上海')
    吃了个饭就晚了。
      

  9.   

    declare @t table(姓名 varchar(10),地区 varchar(10))
    insert into @t select '张三','北京'
    union all select '张三','上海'
    union all select '李四','北京'
    union all select '王五','北京'select 姓名 from @t where 地区 >= all(select '上海' union select '北京')
      

  10.   

    SELECT A.[NAME],COUNT(A.ADDRESS) AS B FROM (SELECT DISTINCT NAME,ADDRESS FROM TABLE1) A
    GROUP BY A.[NAME]
    HAVING COUNT(A.ADDRESS)>=2方法简单