TABLE1:(ID为索引)
ID  Type
========
1    A
2    C
3    A
4    BTABLE2:
ID  Name
========
1   张三
1   王五
2   张三
2   李四
3   李四
3   张三
3   王五
4   王五
4   李四说明:TABLE1中的ID是顺序增加的,TYPE值为A、B、C之一,TABLE1中的ID与TABLE2中的ID是一对多的关系,我想得出每个人ABC类型出现的次数,如下:
Name  A  B  C
=================
张三  2  0  1
李四  1  1  1
王五  2  1  0

解决方案 »

  1.   

    select 
        b.Name,
        A=sum(case Type when 'A' then 1 else 0 end),
        B=sum(case Type when 'B' then 1 else 0 end),
        C=sum(case Type when 'C' then 1 else 0 end)
    from
        Table1 a,Table2 b
    where
        a.ID=b.ID
    group by
        b.Name
      

  2.   

    declare @t1 table(ID int,Type char(1))
    insert into @t1 select 1,'A'
    insert into @t1 select 2,'C'
    insert into @t1 select 3,'A'
    insert into @t1 select 4,'B'declare @t2 table(ID int,name varchar(10))
    insert into @t2 select 1,'张三'
    insert into @t2 select 1,'王五'
    insert into @t2 select 2,'张三'
    insert into @t2 select 2,'李四'
    insert into @t2 select 3,'李四'
    insert into @t2 select 3,'张三'
    insert into @t2 select 3,'王五'
    insert into @t2 select 4,'王五'
    insert into @t2 select 4,'李四'
    select 
        b.Name,
        A=sum(case Type when 'A' then 1 else 0 end),
        B=sum(case Type when 'B' then 1 else 0 end),
        C=sum(case Type when 'C' then 1 else 0 end)
    from
        @T1 a,@T2 b
    where
        a.ID=b.ID
    group by
        b.Name
    /*Name       A           B           C           
    ---------- ----------- ----------- ----------- 
    李四         1           1           1
    王五         2           1           0
    张三         2           0           1
    */
      

  3.   

    create table #t1(ID int,Type char(1))
    insert into #t1 select 1,'A'
    insert into #t1 select 2,'C'
    insert into #t1 select 3,'A'
    insert into #t1 select 4,'B'
    create table #t2(ID int,name varchar(10))
    insert into #t2 select 1,'张三'
    insert into #t2 select 1,'王五'
    insert into #t2 select 2,'张三'
    insert into #t2 select 2,'李四'
    insert into #t2 select 3,'李四'
    insert into #t2 select 3,'张三'
    insert into #t2 select 3,'王五'
    insert into #t2 select 4,'王五'
    insert into #t2 select 4,'李四'declare @sql varchar(256)
    select @sql = ''
    select @sql = @sql + ',[' + type + '] = sum(case type when ''' + type + ''' then 1 else 0 end)' from #t1 group by typeselect @sql 
    exec ('select b.name ' + @sql + ' FROM #t1 a,#t2 b where a.ID=b.ID group by b.Name')