declare @sum numeric(10,2)
select @sum=sum(收入) from t
select 代号,收入=sum(收入),总收入=@sum,占比=cast(sum(收入)/@sum as numeric(5,2))
  from t group by 代号

解决方案 »

  1.   

    create table t(代号  int,              收入    int ,           时间 datetime)insert into t select 1001,                300.00,              '2004-11-6'
    insert into t select 1001,                200.00,             '2004-11-7'
    insert into t select 1002,                150.00,              '2004-11-6'
    insert into t select 1002,                250.00,              '2004-11-7'
    insert into t select 1003,                100.00,              '2004-11-7'select * from t
    select 代号,sum(收入)as 收入,总收入=(select sum(收入)from t),cast(sum(收入)*1.0/(select sum(收入)from t)as decimal(10,1))as 占比 from t group by 代号drop table t
      

  2.   

    每条记录都执行一下select sum(收入)from t,那样效率很低的
      

  3.   

    如果求多个比例呢,比如在加上保险,税金,是不是每个都要select @sum=sum(收入) from t,会不会影响性能呢?
      

  4.   

    如果加入一个条件: WHERE 时间 = '2004-11-7', 该怎么修改呢?
      

  5.   

    select no,aamt =sum(salary) ,allamt =(select sum(salary) from amt), rate = sum(salary)/(select sum(salary) from amt)
     from amt group by no
      

  6.   

    1001                300.00              2004-11-6
    1001                200.00              2004-11-7
    1002                150.00              2004-11-6
    1002                250.00              2004-11-7
    1003                100.00              2004-11-7===================================================================现在要得到如下表:代号                收入                总收入           占比
    ------------------ ------------------- ---------------  --------------------
    1001                500.00              1000.00           0.5
    1002                400.00              1000.00           0.4
    1003                100.00              1000.00           0.1
    select 代号,sum(收入),总收入,sum(收入)/总收入 as 占比 from 
    (select sum(收入) as 总收入 from table_name) a,table_name b
    group by 代号,总收入;