我想弄清楚如何在下面的表格底部获得一个百分比行。
SD a b c d e
D 2168 1545 2163 1540 2153
S 435 212 410 193 391
T 13208 5438 12935 5337 12656
我想将行D和S除以行T以创建两个新的百分比行。这可能吗? 输出看起来像这样:
SD a b c d e
D 2168 1545 2163 1540 2153
S 435 212 410 193 391
T 13208 5438 12935 5337 12656
D/T 0.164 0.284 0.167 0.288 0.170
S/T 0.033 0.04 0.032 0.04 0.031
我只需要百分比,所以这并不一定需要在表中,但如果是,那也很好。
TIA。
答案 0 :(得分:0)
你可以这样做:
select t.sd, t.a, t.b, t.c, t.d, t.e
from t
union all
select sd.sd + '/T', sd.a * 1.0 / t.a, sd.b * 1.0 / t.b, sd.c * 1.0 / t.c,
sd.d * 1.0 / t.d, sd.e * 1.0 / t.d
from t sd cross join
(select t2.* from t t2 where sd = 'T') tt
where sd in ('D', 'S');
虽然实际上这会以您想要的顺序返回行,但这并不能保证。另请注意,最终列将具有相同的类型。
答案 1 :(得分:0)
这很麻烦,但它有效 - 用你的表名替换#temp
select *, row_number() over (order by SD)rownum into #temp2 from #temp
select *from #temp2
union
select 'D/T',(select a from #temp2 where sd='D')/ cast((select a from #temp2 where sd='T') as float),
(select b from #temp2 where sd='D')/ cast((select b from #temp2 where sd='T') as float),
(select c from #temp2 where sd='D')/ cast((select c from #temp2 where sd='T') as float),
(select d from #temp2 where sd='D')/ cast((select d from #temp2 where sd='T') as float),
(select e from #temp2 where sd='D')/ cast((select e from #temp2 where sd='T') as float),
(select max(rownum)+1 from #temp2)
union
select 'S/T',(select a from #temp2 where sd='S')/ cast((select a from #temp2 where sd='T') as float),
(select b from #temp2 where sd='S')/ cast((select b from #temp2 where sd='T') as float),
(select c from #temp2 where sd='S')/ cast((select c from #temp2 where sd='T') as float),
(select d from #temp2 where sd='S')/ cast((select d from #temp2 where sd='T') as float),
(select e from #temp2 where sd='S')/ cast((select e from #temp2 where sd='T') as float),
(select max(rownum)+2 from #temp2)
order by rownum