表A:
id
a
b
c
d表B:
id
a
c
a
c
a结果:
a      1
b      0
c      1
d      0要求:存储过程中处理,可多步,但不能用游标,即不能单笔循环处理
逻辑:对于A表中的id,如果存在于B表中(不论多少),则数量标记为1,否则为0还请不吝赐教,谢谢

解决方案 »

  1.   

    select a,case when exists(select 1 from b where b.id = a.id) then 1 else 0 
    end as count 
    from a
      

  2.   

    select id,case when exists(select 1 from b where b.id = a.id) then 1 else 0 
    end as count 
    from a
      

  3.   

    来迟了,HOHO
    白兄好象动作很快
      

  4.   

    select a,case when exists(select 1 from b where b.id = a.id) then 1 else 0 
    end as count 
    from a
    真快啊,应该正确的
      

  5.   

    用EXISTS,也是逐條數據做判斷的。用關聯來寫,在效率方面更優。
      

  6.   

    --建立測試環境
    Create Table A
    (id Varchar(10))
    Insert A Select  'a'
    Union All Select 'b'
    Union All Select 'c'
    Union All Select 'd'Create Table B
    (id Varchar(10))
    Insert B Select  'a'
    Union All Select 'c'
    Union All Select 'a'
    Union All Select 'c'
    Union All Select 'a'
    GO
    --測試
    Select 
    A.id,
    (Case When B.id Is Not Null Then 1 Else 0 End) As 标记
    From
    A
    Left Join
    (Select Distinct id From B) B
    On A.id = B.id
    GO
    --刪除測試環境
    Drop Table A, B
    --結果
    /*
    id 标记
    a 1
    b 0
    c 1
    d 0
    */
      

  7.   

    同意 paoluo(一天到晚游泳的鱼)
      

  8.   

    或者:
    select a.id ,isnull(bb.flag,0) as flag  
    from a 
    left outer join (select distinct id,1 as flag from b) as BB
    on a.id = bb.id
      

  9.   

    个人觉得 用left outer join的效率高点~~
      

  10.   

    谢谢各位或者:
    select a.id ,isnull(bb.flag,0) as flag  
    from a 
    left outer join (select distinct id,1 as flag from b) as BB
    on a.id = bb.id
    -------------------------------有个问题是,现在我不能直接select distinct id,1 as flag from b这样做,数据太多了,要限制b的id
      

  11.   

    數據多,用Distinct處理,效果會好些。
      

  12.   

    select  distinct  a.id
    ,( case when  a.id in (select b.id from  b) then 1 else 0  end  )  as state
    from  a
      

  13.   

    select id,case when exists(select 1 from b where b.id = a.id) then 1 else 0 
    end as count 
    from a