select sum(表1.aa) as a1,sum(表1.bb) as a2,sum(表1.cc) as a3 from 表1 

解决方案 »

  1.   

    a1 a2 a3 要从表2中读出。
      

  2.   

    declare @Sql nvarchar(1000)
    set @Sql=''
    select @Sql=@Sql+ 'sum(' + 字段1 + ') as ' + 字段2 + ', ' from 表2
    print @Sql
    select @Sql= 'select ' + left(@Sql,len(@Sql)-1) + 'from 表1'
    EXEC (@Sql)结果:
    a1          a2          a3          
    ----------- ----------- ----------- 
    30          60          50
      

  3.   

    要利用表2中的对应关系,比如我只统计aa和bb
    就应该是:
    字段名:a1   a2   
    记录:  30   60   
    一定要在表2中做查询,因为选择的字段aa bb cc是不定的!!
      

  4.   

    declare @Sql nvarchar(8000)
    set @Sql=''
    select @Sql=@Sql+ 'sum(' + 表2.字段1 + ') as ' + 表2.字段2 + ', ' from 表2
    print @Sql
    select @Sql= 'select ' + left(@Sql,len(@Sql)-1) + 'from 表1'
    EXEC (@Sql)
      

  5.   

    declare @Sql nvarchar(8000)
    set @Sql=''
    select @Sql=@Sql+ 'sum(' + 表2.字段1 + ') as ' + 表2.字段2 + ', ' from 表2 where 你的选择条件
    print @Sql
    select @Sql= 'select ' + left(@Sql,len(@Sql)-1) + 'from 表1'
    EXEC (@Sql)
      

  6.   


    SELECT B.Field1 ,C.Total FROM Table1 B LEFT JOIN (SELECT A.Field1,SUM(A.Field2)AS TOTAL FROM Table1 GROUP BY  A.Field1)C  ON B.Field1=A.Field1
      

  7.   

    一个比较灵活的处理CREATE PROCEDURE test @name varchar(30) AS
    set nocount on
      declare @vColumn varchar(50)
      declare @sql varchar(5000)
      select @vColumn =b2 from a2 where b1=@name
      select @sql='select sum('+@name+')'+'as '+@vColumn +'from a1'
      exec(@sql) a1是表1 a2是表2
    @name是要查询的表1的列名
    b1是表2的字段1  b2是表2的字段2
    当然,你的问题上述存储过程不能完全解决,但是可以用此思路。
    那时@name应该是要查询的列组成的字符串(中间有特定的分隔符隔开)
     在存储过程中取出一个一个的列名,再动态的合成@sql即可。那时要注意异常处理
      

  8.   

    select sum((select top 1  字段2 from 表2),
     sum(select * (select top 2 字段2  from 表2 where 字段2 not in(select top1 字段2 from 表2)),
     sum(select * (select top 3 字段2  from 表2 where 字段2 not in(select top2 字段2 from 表2)),
     sum
     sum...
     from 表1
    这个sql语句肯定可以搞定,不知道你看不看的懂 呵呵
    按如上的规律 sum 50次,只要你的表1的字段数目<=50,就没有问题。
    不过要是写成存储过程,就很简单了。