tb1Pid gender
1  Female
2  Female
3  Null(空值)
4  Null
5  Male
6  Maletb2eid Pid
aa   1
bb   2
cc   3我希望得到有多少Female,多少Male,多少Null
正确的返回是
2  Female
1  Null
0  Male
谢谢

解决方案 »

  1.   

    create table #tb1 (pid int,gender varchar(100))
    create table #tb2 (eid varchar(100),pid int)insert into #tb1 
    select 1,  'Female' union all
    select 2,  'Female' union all
    select 3,  Null union all
    select 4,  Null union all
    select 5,  'Male' union all
    select 6,  'Male'insert into #tb2
    select 'aa',   1 union all
    select 'bb',   2 union all
    select 'cc',   3
    select gender,sum(cnt) as 记录数
    from
    (
    select gender,(select count(*) from #tb2 where pid=t1.pid) as cnt
    from #tb1 as t1
    ) t2
    group by genderdrop table #tb1
    drop table #tb2
      

  2.   

    create table #tb1 (pid int,gender varchar(100))
    create table #tb2 (eid varchar(100),pid int)insert into #tb1 
    select 1,  'Female' union all
    select 2,  'Female' union all
    select 3,  Null union all
    select 4,  Null union all
    select 5,  'Male' union all
    select 6,  'Male'insert into #tb2
    select 'aa',   1 union all
    select 'bb',   2 union all
    select 'cc',   3
    select gender,sum(cnt) as 记录数
    from
    (
    select gender,(select count(*) from #tb2 where pid=t1.pid) as cnt
    from #tb1 as t1
    ) t2
    group by genderdrop table #tb1
    drop table #tb2
    --查询结果/*
    gender    记录数
    ----------------
    NULL      1
    Female    2
    Male      0*/
      

  3.   

    借一楼的数据
    select sum(ss) 记录数,gender
    from
    (select (select count(*) from #tb2 where pid=#tb1.pid) as ss,gender
    from #tb1)t
    group by gender
    order by sum(ss) desc
      

  4.   

    create table #tb1 (pid int,gender varchar(100))
    create table #tb2 (eid varchar(100),pid int)insert into #tb1 
    select 1,  'Female' union all
    select 2,  'Female' union all
    select 3,  Null union all
    select 4,  Null union all
    select 5,  'Male' union all
    select 6,  'Male'insert into #tb2
    select 'aa',   1 union all
    select 'bb',   2 union all
    select 'cc',   3--按记录数多少降序排列
    select gender,sum(cnt) as 记录数
    from
    (
    select gender,(select count(*) from #tb2 where pid=t1.pid) as cnt
    from #tb1 as t1
    ) t2
    group by gender
    order by sum(cnt) descdrop table #tb1
    drop table #tb2
    --查询结果/*
    gender    记录数
    ----------------
    Female    2
    NULL      1
    Male      0*/
      
      

  5.   

    我的tb1,tb2在同一server下的不同数据库,那个query不成功
      

  6.   

    tb1,tb2在同一server下的不同数据库 也没有关系啊tb1换成db1.dbo.tb1
    tb2换成db2.dbo.tb2不就行了