表一tb1,cA里面有三个值
a, b, null(空值)
表二 tb2,里面数据如下
c1,cA
1  a
2  a
3  null
4  null我想知道tb2中到底有多少个a,多少个b,多少个null我用
select count(isnull(tb1.cA,'')),tb1.cA from tb1 left join bt2 on
tb1.cA=tb2.cA得到的结果是
2 a
2 null
我想得到的结果是2 a
2 null
0 b如何得到呢
谢谢

解决方案 »

  1.   

    select cA,(select sum(1) from tb2 where isnull(tb2.ca,'')=isnull(tb1.ca,'')) from tb1;
      

  2.   

    create table tb1(cA varchar(10))
    insert tb1 select 'a' union select 'b' union select nullcreate table tb2(c1 int, cA varchar(10))
    insert tb2 select 1,'a' union select 2,'a' union select 3,null union select 4,null
    select cA,cnt=(select count(cA) from tb2 b where isnull(b.cA,'A')=isnull(a.cA,'A')) from tb1 a group by cA
      

  3.   


    declare @tb1 table(cA varchar(10))
    insert @tb1 select 'a'
    union all select  'b'
    union all select  nulldeclare @tb2 table(
    c1 int,
    cA varchar(10)
    )
    insert @tb2 select 
    1,  'a'
    union all select 
    2,  'a'
    union all select 
    3,  null
    union all select 
    4,  nullselect count(tb2.c1),tb1.cA from @tb1 tb1 left join @tb2 tb2 on
    tb1.cA=tb2.cA or ( tb1.cA is null and tb2.cA is null)
    group by tb1.cA--结果
               cA         
    ----------- ---------- 
    2           NULL
    2           a
    0           b(所影响的行数为 3 行)警告: 聚合或其它 SET 操作消除了空值。
      

  4.   

    --创建测试环境
    create table tb1(cA varchar(10))
    create table tb2(c1 int,cA varchar(10))
    --插入测试数据
    insert tb1(cA)
    select 'a' union all
    select 'b' union all
    select nullinsert tb2(c1,cA)
    select '1','a' union all
    select '2','a' union all
    select '3',null union all
    select '4',null--求解过程
    select tb1.cA,sum(case when tb2.cA is null and tb1.cA is not null then 0 else 1 end) as 个数
    from tb1 
    left join tb2 on isnull(tb1.cA,'') = isnull(tb2.cA,'')
    group by tb1.cA--删除测试环境
    drop table tb1,tb2/*--测试结果
    cA         个数          
    ---------- ----------- 
    NULL       2
    a          2
    b          0(所影响的行数为 3 行)
    */