注册 登录
编程论坛 SQL Server论坛

sql语句求助(大侠们帮帮忙)

ch756132352 发布于 2012-08-07 10:47, 646 次点击
集团公司A有三个子公司x,y,z
已知三子公司的09,10,11利润数据
想用sql语句求每年每个子公司对集团公司的利润贡献比率
表(例子)
公司  时间  利润
x    09     1
x    10     2
x    11     3
y    09     2
y    10     3
y    11     4
z    09     3
z    10     4
z    11     5
大侠们帮帮忙,谢谢!

[ 本帖最后由 ch756132352 于 2012-8-7 11:22 编辑 ]
5 回复
#2
CXP07142012-08-07 14:07

select 公司,a.datetime 时间,sum(a.lr)/b.sumlr 利润比率
from table_1 a,(select sum(isnull(lr,0)) as sumlr from table_1) b
group by ,a.datetime,b.sumlr

结果:
公司  时间  利润比率
x    09    0.037037
y    09    0.074074
z    09    0.111111
x    10    0.074074
y    10    0.111111
z    10    0.148148
x    11    0.111111
y    11    0.148148
z    11    0.185185
希望是这样子
#3
CXP07142012-08-07 14:13

select 公司,a.datetime 时间,sum(a.lr)/b.sumlr 利润比率
from table_1 a left join (select datetime,sum(isnull(lr,0)) as sumlr from table_1 group by datetime) b on a.datetime=b.datetime
group by ,a.datetime,b.sumlr

x    09    0.166666
x    10    0.222222
x    11    0.250000
y    09    0.333333
y    10    0.333333
y    11    0.333333
z    09    0.500000
z    10    0.444444
z    11    0.416666
#4
dlmu_wang2012-08-07 15:02
--测试数据
drop table test
go
create table test
(g char(1),y char(2),gx int)
go

insert test
select
'x','09', 1
union select
'x','10', 2
union select
'x','11', 3
union select
'y','09', 2
union select
'y','10', 3
union select
'y','11', 4
union select
'z','09', 3
union select
'z','10', 4
union select
'z','11', 5
go
--

select a.g,a.y,convert(varchar(20),a.gx*100.00/(select sum(gx) from test where y=a.y))+'%' 贡献率 from test a
go
/*结果
x    09    16.6666666666666%
x    10    22.2222222222222%
x    11    25.0000000000000%
y    09    33.3333333333333%
y    10    33.3333333333333%
y    11    33.3333333333333%
z    09    50.0000000000000%
z    10    44.4444444444444%
z    11    41.6666666666666%
*/
#5
shangxisen2012-08-07 16:25
select *,利润/zlr from tabel,
(select sum(利润) zlr,时间 from Table group by 时间)table2
where table.时间=table2.时间
#6
netlin2012-08-08 12:26
更喜欢 5楼的方法。
1