使用win 7上SQL Server 2008R2中另一个表中的列计算填充表列
我需要在Win7上的SQLServer2008R2中填充一个表列 表1使用win 7上SQL Server 2008R2中另一个表中的列计算填充表列,sql,sql-server,windows-7,sql-server-2008-r2,Sql,Sql Server,Windows 7,Sql Server 2008 R2,我需要在Win7上的SQLServer2008R2中填充一个表列 表1 Id1 Id2 value1 --------------------- 1 a 58218 1 b 2888 1 c 916 我需要创建一个表2,以便 Id1 value1 value1_b_over_a value1_c_over_a -------------------
Id1 Id2 value1
---------------------
1 a 58218
1 b 2888
1 c 916
我需要创建一个表2,以便
Id1 value1 value1_b_over_a value1_c_over_a
------------------------------------------------------
1 58218 2888/58218 916/58218
我希望只使用一个SQL查询获取表
任何帮助都将不胜感激 您可以通过条件聚合来实现这一点:
select t1.id1,
sum(case when id2 = 'a' then value1 end) as value1,
sum(case when id2 = 'b' then value1 end) / sum(case when id2 = 'a' then value1 end) as value1_b_over_a,
sum(case when id2 = 'c' then value1 end) / sum(case when id2 = 'a' then value1 end) as value1_c_over_a,
from table1 t1
group by t1.id1;
注意:SQLServer执行整数运算。如果需要数字,请将value1
转换为适当的数字类型
select t1.id1,
sum(case when id2 = 'a' then value1 end) as value1,
sum(case when id2 = 'b' then cast(value1 as float) end) / sum(case when id2 = 'a' then value1 end) as value1_b_over_a,
sum(case when id2 = 'c' then cast(value1 as float) end) / sum(case when id2 = 'a' then value1 end) as value1_c_over_a,
from table1 t1
group by t1.id1;
您可以先做一个简单的枢轴,然后再进行操作
select result.id1,
result.a value1,
cast(result.b as decimal) / result.a value1_b_over_a,
cast(result.c as decimal) / result.a value1_c_over_a
from (
select *
from table1 t
pivot(sum(value1) for id2 in (
[a],
[b],
[c]
)) as pivotrow
) result;