select a.a,b.a as a1,a.b,b.b as b1,a.c,b.c as c1  from 表1 a inner join 表2 b on a.机房=b.机房

解决方案 »

  1.   

    你要动态的话
    只能用动态sql 了
    从columns里面找列
      

  2.   

    a1,b1,c1...等能否动态生成?因为事先不知道有那些?
      

  3.   

    我就拿你的例子来做说明吧!我把你的例子做两个列不同的交叉表,然后合并起来。因为是针对的一个例子,所以要简单一些,如果是多个,那么你要照思路适当修改才行![create] table t1
    (代理商 varchar(20),机房 int,用户名 varchar(20))[create] table t2
    (代理商 varchar(20))[create] table t3
    (机房 int)insert t1 values ('A',1,'张')
    insert t1 values ('A',1,'黄')
    insert t1 values ('B',1,'李')
    insert t1 values ('C',2,'陈')
    insert t1 values ('A',2,'王')insert t2 values ('A')
    insert t2 values ('B')
    insert t2 values ('C')
    insert t2 values ('D')insert t3 values (1)
    insert t3 values (2)
    insert t3 values (3)
    insert t3 values (4)declare @sql varchar(8000),@sql1 varchar(8000),@sql2 varchar(2000)select @sql='select b.机房',@sql1='select b.机房',@sql2=''select @sql=@sql+',['+b.代理商+']=sum(case when 代理商='''+b.代理商+''' 
    then 1 else 0 end)',
           @sql1=@sql1+',['+b.代理商+'1]=sum(case when 代理商='''+b.代理商+''' 
    then 1 else 0 end)',
           @sql2=@sql2+',['+b.代理商+'],['+b.代理商+'1]'
    from t1 a
    right join t2 b
    on a.代理商=b.代理商
    group by b.代理商select @sql=@sql+' from t1 a right join t3 b on a.机房=b.机房 group by b.机房',
           @sql1=@sql1+' from t1 a right join t3 b on a.机房=b.机房 group by b.机房'
    exec(@sql)
    exec(@sql1)
    exec('select a.机房'+@sql2+' from ('+@sql+') a inner join ('+@sql1+') b on a.机房=b.机房')drop table t1
    drop table t2
    drop table t3机房          A           B           C           D           
    ----------- ----------- ----------- ----------- ----------- 
    1           2           1           0           0
    2           1           0           1           0
    3           0           0           0           0
    4           0           0           0           0机房          A1          B1          C1          D1          
    ----------- ----------- ----------- ----------- ----------- 
    1           2           1           0           0
    2           1           0           1           0
    3           0           0           0           0
    4           0           0           0           0机房          A           A1          B           B1          C           C1          D           D1          
    ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- 
    1           2           2           1           1           0           0           0           0
    2           1           1           0           0           1           1           0           0
    3           0           0           0           0           0           0           0           0
    4           0           0           0           0           0           0           0           0
      

  4.   

    十分感谢 samfeng_2003(风云) 写的例子和思路,还有churchatp1提的“从columns里面找列”的思路,不过如果churchatp1有例子就更好了。谢谢二位,分数给上,不多,包涵!