A_ID B_ID C
1 11 a
1 12 b
1 13 c
1 14 a
2 21 a
2 22 a
2 23 a
3 31 c
3 32 a
4 41 a
查询表中A_ID一致,且C值全为a的A_ID,该表中这样的A_ID为2和4.
非常感谢!

解决方案 »

  1.   


    create table hua
    (A_ID int, B_ID int, C varchar(2))insert into hua
    select 1, 11, 'a' union all
    select 1, 12, 'b' union all
    select 1, 13, 'c' union all
    select 1, 14, 'a' union all
    select 2, 21, 'a' union all
    select 2, 22, 'a' union all
    select 2, 23, 'a' union all
    select 3, 31, 'c' union all
    select 3, 32, 'a' union all
    select 4, 41, 'a'
    select x.A_ID
    from hua x
    group by x.A_ID
    having count(1)=
    (select sum(case y.C when 'a' then 1 else 0 end) 'sa'
     from hua y where y.A_ID=x.A_ID)/*
    A_ID
    -----------
    2
    4(2 row(s) affected)
    */
      

  2.   

    SELECT * FROM tb a WHERE NOT EXISTS(SELECT 1 FROM tb WHERE a.a_id=a_id AND a.c<>c ) AND c='a'
      

  3.   


    declare @t table(
     A_ID int,
     B_ID int,
     C varchar(6)
    )
    insert into @t 
    select 1,11,'a' union all
    select 1,12,'b' union all
    select 1,13,'c' union all
    select 1,14,'a' union all
    select 2,21,'a' union all
    select 2,22,'a' union all
    select 2,23,'a' union all
    select 3,31,'c' union all
    select 3,32,'a' union all
    select 4,41,'a'
    ;with cte as(
      select distinct  a_id,c from @t
    )select a_id, count(1)
    from cte
    group by a_id
    having(count(1)=1)
      

  4.   

    SELECT A.*
    FROM dbo.hua AS A
    INNER JOIN
    (
    SELECT A_ID
    FROM
    (
    SELECT A_ID, C
    FROM dbo.hua
    GROUP BY A_ID, C
    ) AS A
    GROUP BY A_ID
    HAVING COUNT(C) = 1
    ) AS B ON A.A_ID = B.A_ID
    WHERE A.C = 'a'
      

  5.   

    with t
    as
    (
    select *
    from
    (
    select 1 as a_id, 11 as b_id, 'a' as c union all
    select 1, 12, 'b' union all
    select 1, 13, 'c' union all
    select 1, 14, 'a' union all
    select 2, 21, 'a' union all
    select 2, 22, 'a' union all
    select 2, 23, 'a' union all
    select 3, 31, 'c' union all
    select 3, 32, 'a' union all
    select 4, 41, 'a'
    )a
    )select t.a_id
    from t
    inner join 
          (
    select t.a_id,COUNT(*) as r_num
    from t
    group by t.a_id
          )tt
          on t.a_id = tt.a_id
    where t.c = 'a'
    group by t.a_id
    having count(t.a_id) = max(tt.r_num)