34,576
社区成员
发帖
与我相关
我的任务
分享
-- 2000 还不简单
select
id,
ir_avg = max(case kind when 'ir' then avg end),
ir_max = max(case kind when 'ir' then max end),
ir_min = max(case kind when 'ir' then min end),
mld_avg = max(case kind when 'mld' then avg end),
mld_max = max(case kind when 'mld' then max end),
mld_min = max(case kind when 'mld' then min end)
from #b
group by id
--> 测试数据:#a
if object_id('tempdb.dbo.#a') is not null drop table #a
create table #a(id int, db varchar(8))
insert into #a
select 1, 'sss' union all
select 2, 'aaa'
--> 测试数据:#b
if object_id('tempdb.dbo.#b') is not null drop table #b
create table #b(id int, kind varchar(8), avg int, max numeric(2,1), min numeric(2,1))
insert into #b
select 1, 'ir', 2, 4, 1 union all
select 1, 'mld', 3, 3.4, 2.3 union all
select 1, 'mcd', 3, 4, 3 union all
select 2, 'ir', 1, 3, 1 union all
select 2, 'mld', 3, 3, 1 union all
select 2, 'mcd', 3, 3, 1
select * from
(
select a.db, b.* from #a a,
(
select id,kind+'_avg' kind, avg val from #b union all
select id,kind+'_min' kind, min val from #b union all
select id,kind+'_max' kind, max val from #b
) b
where a.id=b.id
) t
pivot (max(val) for kind in (ir_avg,ir_max,ir_min,mld_avg,mld_max,mld_min,mcd_avg,mcd_max,mcd_min)) p
/*
db id ir_avg ir_max ir_min mld_avg mld_max mld_min mcd_avg mcd_max mcd_min
-------- ----------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
sss 1 2.0 4.0 1.0 3.0 3.4 2.3 3.0 4.0 3.0
aaa 2 1.0 3.0 1.0 3.0 3.0 1.0 3.0 3.0 1.0
*/