table1 table2
地区 元素 含量 地区 au fe al mg cu
a fe 20 a 0 20 30 20 0
a al 30 b 10 0 6 5 9
a mg 20 c 0 5 0 6 0
b au 10
b mg 5
b al 6
b cu 9
c fe 5
c mg 6
求sql语句如何把table 1的值 如上 插入到table2?
地区 元素 含量 地区 au fe al mg cu
a fe 20 a 0 20 30 20 0
a al 30 b 10 0 6 5 9
a mg 20 c 0 5 0 6 0
b au 10
b mg 5
b al 6
b cu 9
c fe 5
c mg 6
求sql语句如何把table 1的值 如上 插入到table2?
insert into t1
select 'a','fe',20 union all
select 'a','al',30 union all
select 'a','mg',20 union all
select 'b','au',10 union all
select 'b','mg',5 union all
select 'b','al',6 union all
select 'b','cu',9 union all
select 'c','fe',5 union all
select 'c','mg',6
select
地区,
sum(case when 元素='au' then 含量 else 0 end) as au,
sum(case when 元素='fe' then 含量 else 0 end) as fe,
sum(case when 元素='al' then 含量 else 0 end) as al,
sum(case when 元素='mg' then 含量 else 0 end) as mg,
sum(case when 元素='cu' then 含量 else 0 end) as cu
from t1
group by 地区drop table t1/*
table2
地区 au fe al mg cu
a 0 20 30 20 0
b 10 0 6 5 9
c 0 5 0 6 0
*/
create table t1(地区 varchar(10), 元素 varchar(10), 含量 int)
insert into t1
select 'a','fe',20 union all
select 'a','al',30 union all
select 'a','mg',20 union all
select 'b','au',10 union all
select 'b','mg',5 union all
select 'b','al',6 union all
select 'b','cu',9 union all
select 'c','fe',5 union all
select 'c','mg',6
--行转列
Declare @S Varchar(8000)
Select @S = 'Select 地区'
Select @S = @S + ', SUM(Case 元素 When ''' + 元素 + ''' Then 含量 Else 0 End) As ' + 元素
From t1 Group By 元素
Select @S = @S + ' From t1 Group By 地区'
EXEC(@S)drop table t1
地区 al au cu fe mg
---------- ----------- ----------- ----------- ----------- -----------
a 30 0 0 20 20
b 6 10 9 0 5
c 0 0 0 5 6