我有一张像下面这样具有巨大价值的桌子。 ' FBB'类型值将在稍后的表的SERVICE列中添加。
SITE_NAME SERVICE BANDWIDTH
MBCGP1 3g 30
BONWRT 3g 40
BORNR1 3g 30
MBCGP1 2g 8
BONWRT 2g 4
BORNR1 2g 8
BOSBB1 2g 8
我想在这样的表中插入这些值。
SITE_NAME 2g_bw 3g_bw fbb_bw
MBCGP1 8 30 0
BONWRT 4 40 0
BORNR1 8 30 0
BOSBB1 8 0 0
我不知道如何编写一个sql。
答案 0 :(得分:2)
您可以将表的实例用于2g,将另一个用于3g,然后将这些表连接起来。
select 2g.site_name, 2g.bandwidth 2g_bw, 3g.bandwidth 3g_bw, 0 fbb_bw
from yourtable 2g
join yourtable 3g
on 3g.site_name = 2g.site_name
and 3g.service = '3g'
where 2g.service = '2g'
然后,您可以将结果插入另一个包含INSERT ... SELECT
insert into othertable (site_name, 2g_bw, 3g_bw, fbb_bw)
select 2g.site_name, 2g.bandwidth 2g_bw, 3g.bandwidth 3g_bw, 0 fbb_bw
from yourtable 2g
join yourtable 3g
on 3g.site_name = 2g.site_name
and 3g.service = '3g'
where 2g.service = '2g'
正如@Strawberry建议的那样,你可以使用完全连接来获得2g或3g(不是两者)的空值。
select 2g.site_name, 2g.bandwidth 2g_bw, 3g.bandwidth 3g_bw, 0 fbb_bw
from yourtable 2g
left outer join yourtable 3g
on 3g.site_name = 2g.site_name
and 3g.service = '3g'
where 2g.service = '2g'
union
select 3g.site_name, 2g.bandwidth 2g_bw, 3g.bandwidth 3g_bw, 0 fbb_bw
from yourtable 3g
left outer join yourtable 2g
on 2g.site_name = 3g.site_name
and 2g.service = '2g'
where 3g.service = '3g'
第一个请求获得2G和3G相关的结果,第二个结果与3G和2G相关联。如果您将结果联合起来,那么肯定会检索所有结果。